简体   繁体   中英

How to deserialize list of objects from json

Thats my class.

class MyClass1 : IInterface1
{
    public MyClass1()
    {
        this.Interface2s = new List<IInterface2>();
    }

    public string strI1 { get; set; }
    public int intI1 { get; set; }
    public IList<IInterface2> Interface2s { get; set; }
    public int intC1 { get; set; }
}

In application I serialized it with some random values. Result:

{
  "strI1": "strI1",
  "intI1": 2,
  "Interface2s": [
    {
      "intI2": 111
    },
    {
      "intI2": 222
    },
    {
      "intI2": 333
    }
  ]
}

Then, i want to deserialize that string back, but I'm loosing values in my IList

result of deserialization next:
{
  "strI1": "strI1",
  "intI1": 2,
  "Interface2s": [
    {
      "intI2": 0
    },
    {
      "intI2": 0
    },
    {
      "intI2": 0
    }
  ]
}

To deserialize interface I'm using that example http://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm

I need to deserialize values in list too. Any suggestions?

My advice is just use http://www.newtonsoft.com/json

JsonConvert.SerializeObject(target)

and to deserialize

JsonConvert.DeSerializeObject<MyClass1>(target)

And it should just be as simple as that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM