2010-10-13 35 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 ...

相关问题