2012-09-27 55 views
0

我有一個System.Object的擴展方法來使用Json.Net序列化和反序列化對象。這是我的擴展方法:對象序列化/反序列化不起作用

public static void SaveToFile(this object data, string FileName) 
{ 
    using (StreamWriter writer = new StreamWriter(FileName)) 
    { 
     string encode = WpfApplication.Helper.Encrypt(JsonConvert.SerializeObject(data)); 
     writer.Write(encode); 
     writer.Close(); 
    } 
} 

public static void LoadFromFile<t>(this object data, string FileName) 
{ 
    using (StreamReader reader = new StreamReader(FileName)) 
    { 

     data = JsonConvert.DeserializeObject<t>(WpfApplication.Helper.Decrypt(reader.ReadToEnd())); 
     reader.Close(); 
    } 
} 

和這是我想反序列化類:

public class CardPack 
{ 
    #region Properties 
    private string name; 

    public string Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 

    private List<FlashCard> cards; 

    public List<FlashCard> Cards 
    { 
     get { return cards; } 
     set { cards = value; } 
    } 

    private bool registered; 
    public bool Registered 
    { 
     get { return registered; } 
     set { registered = value; } 
    } 

    private int currentCardIndex; 

    public int CurrentCardIndex 
    { 
     get { return currentCardIndex; } 
     set { currentCardIndex = value; } 
    } 

    public string RegisterKey { get; set; } 

    public string ViewName { get; set; } 

    public List<FlashCard> TodayCards { get; set; } 
    #endregion 
    ~CardPack() 
    { 
     foreach (FlashCard card in cards) 
     { 
      card.Check(); 
     } 
     currentCardIndex = 0; 
     TodayCards = null; 
     this.SaveToFile(string.Format(System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Split(@"file:\\")[1] + @"\Packs\{0}.json", name)); 
    } 

但每當我反序列化類cards是空的,我不知道如何解決這個問題。有誰能夠幫助我?

更新 我找到錯誤,當我有這樣的代碼:

public CardPack(string Name) 
    { 
     this.name = Name; 
     this.LoadFromFile<CardPack>(string.Format(System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Split(@"file:\\")[1] + @"\Packs\{0}.json", name)); 
     foreach (var item in cards) 
     { 
      if (item.NextTime == null) 
      { 
       int a = 0; 
      } 
     } 
     TodayCards = cards.Where(c => c.NextTime.Date == DateTime.Today).ToList(); 
    } 

,因爲應用程序關閉時,它試圖運行foreach (var item in cards)!我問here,發現cards是空的!

update2我序列化了CardPack對象,其結構有點不同。在之前的結構中Cards屬性是隻讀的。

回答

0

我發現data = JsonConvert.DeserializeObject<t>(WpfApplication.Helper.Decrypt(reader.ReadToEnd()));在擴展方法中不會更改爲'數據'類,那麼CardsCardPack中始終爲空。我會問一個問題,以找出爲什麼我不能從後面的擴展方法中設置類。