简体   繁体   English

如何从JSON反序列化对象列表

[英]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 然后,我想反序列化该字符串,但是我正在丢失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 要反序列化接口,我使用的是该示例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 我的建议只是使用http://www.newtonsoft.com/json

JsonConvert.SerializeObject(target)

and to deserialize 并反序列化

JsonConvert.DeSerializeObject<MyClass1>(target)

And it should just be as simple as that. 它应该就这么简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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