Rise Against
Rise Against

Reputation: 23

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?

Upvotes: 0

Views: 1231

Answers (1)

gmn
gmn

Reputation: 4319

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.

Upvotes: 2

Related Questions