开发者

Serialize And Deserialize Object Graph To and From String Key/Value Pair

Assuming the following model

public class MyObject
{
    public string Name { get; set; }
    public ICollection<M开发者_如何学PythonyObjectItem> Items { get; set; }
}

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

I want to serialize and deserialize this object graph to a list of key/value pair of strings like :

MyObject.Name - "Name"

MyObject.Items.0.Name - "Name1"

MyObject.Items.0.Total - "10"

MyObject.Items.1.Name - "Name2"

MyObject.Items.1.Total - "20"


Object serialization is usually expensive for big xml structures. If it's possible, try to use XMlWriter or XmlTextWriter - usage example: http://dotnetperls.com/xmlwriter


Well, you could not use a built-in serializer for that, you would need a custom ToString() / Parse(), similar to this: (ToString() is kind of self explanatory)

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;

Hope this helps, as I do not have access to a C# IDE at this time...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜