【问题标题】:Serialize And Deserialize Object Graph To and From String Key/Value Pair序列化和反序列化对象图到字符串键/值对和从字符串键/值对
【发布时间】:2010-10-13 18:25:58
【问题描述】:

假设如下模型

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 - "Name1"

MyObject.Items.0.Total - “10”

MyObject.Items.1.Name - "Name2"

MyObject.Items.1.Total - “20”

【问题讨论】:

  • 尝试将ICollection更改为List

标签: c# serialization


【解决方案1】:

对于大型 xml 结构,对象序列化通常很昂贵。如果可能,请尝试使用XMlWriterXmlTextWriter - 用法示例:http://dotnetperls.com/xmlwriter

【讨论】:

    【解决方案2】:

    好吧,你不能为此使用内置的序列化程序,你需要一个自定义的 ToString() / Parse(),类似于:(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...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多