小编典典

将嵌套的JSON反序列化为C#对象

json

我从看起来像这样的API获取JSON:

{
  "Items": {
    "Item322A": [{
      "prop1": "string",
      "prop2": "string",
      "prop3": 1,
      "prop4": false
    },{
      "prop1": "string",
      "prop2": "string",
      "prop3": 0,
      "prop4": false
    }],
       "Item2B": [{
      "prop1": "string",
      "prop2": "string",
      "prop3": 14,
      "prop4": true
    }]
  },
  "Errors": ["String"]
}

我尝试了几种方法来在c#对象中表示此JSON(太多内容无法在此处列出)。我已经尝试过使用列表和字典,这是我尝试表示它的最新示例:

    private class Response
    {
        public Item Items { get; set; }
        public string[] Errors { get; set; }
    }

    private class Item
    {
        public List<SubItem> SubItems { get; set; }
    }

    private class SubItem
    {
        public List<Info> Infos { get; set; }
    }

    private class Info
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public int Prop3 { get; set; }
        public bool Prop4 { get; set; }
    }

这是我用来反序列化JSON的方法:

    using (var sr = new StringReader(responseJSON))
    using (var jr = new JsonTextReader(sr))
    {
        var serial = new JsonSerializer();
        serial.Formatting = Formatting.Indented;
        var obj = serial.Deserialize<Response>(jr);
    }

obj包含ItemsErrors。并且Items包含SubItems,但是SubItemsnull。因此,除了Errors反序列化之外,什么都没有。

它应该很简单,但是由于某种原因我无法弄清楚正确的对象表示形式


阅读 393

收藏
2020-07-27

共1个答案

小编典典

"Items"使用Dictionary<string, List<Info>>,即:

class Response
{
    public Dictionary<string, List<Info>> Items { get; set; }
    public string[] Errors { get; set; }
}

class Info
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public int Prop3 { get; set; }
    public bool Prop4 { get; set; }
}

假设项目名称"Item322A""Item2B"随响应而变化,并且将这些名称作为字典键读取。

样品提琴

2020-07-27