2010-10-13 197 views
-2

假設下面的模型序列化和反序列化對象圖,並從字符串鍵/值對

public class MyObject 
{ 
    public string Name { get; set; } 
    public ICollection<MyObjectItem> Items { get; set; } 
} 

public class MyObjectItem 
{ 
    public string Name { get; set; } 
    public int Total { get; set; } 
} 

我想序列化和反序列化這個對象圖鍵/值對像字符串列表:

MyObject.Name - 「名稱」

MyObject.Items.0.Name - 「名1」

MyObject.Items.0.Total - 「10」

MyObject.Items.1.Name - 「名稱2」

MyObject.Items.1.Total - 「20」

+1

擊掌。有問題嗎? – 2010-10-13 18:35:55

+0

嘗試將'ICollection'更改爲'List' – SwDevMan81 2010-10-13 18:49:25

回答

0

好了,你不能使用內置串行的,你需要一個定製的ToString()/解析(),與此類似: (toString()方法是一種自我解釋的)

MyObject obj = new MyObject();  

List<MyObjectItem> items = new List<MyObjectItem>();  

foreach (string line in text.Split) 
{ 
    // skip MyObject declaration int idx = line.IndexOf('.'); 
    string sub = line.Substring(idx); 
    if (sub.StartsWith("Name")) { 
     obj.Name = sub.Substring("Name".Length + 3 /* (3 for the ' - ' part) */); 
    } 
    else 
    { 
      sub = sub.Substring("Items.".Length); 
      int num = int.Parse(sub.Substring(0, sub.IndexOf('.')); 
      sub = sub.Substring(sub.IndexOf('.' + 1); 
      if (items.Count < num) 
       items.Add(new MyObjectItem()); 
      if (sub.StartsWith("Name")) 
      { 
       items[num].Name = sub.SubString("Name".Length + 3); 
      } 
      else 
      { 
       items[num].Total = sub.SubString("Total".Length + 3); 
      } 
    } 
} 

obj.Items = items; 

希望這會有所幫助,因爲我沒有在這個時候訪問C#IDE ...

相關問題