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

问题描述:

我正在从如下所示的API获取JSON:

I am getting JSON back from an API that looks like this:

{
  "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(在此列出太多).我已经尝试过使用列表和词典,这是我尝试表示它的最新示例:

I have tried a few approaches to represent this JSON in c# objects (too many to list here). I've tried with lists and dictionaries, here is a recent example of how I've tried to represent it:

    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的方法:

And here is the method I am using to deserialize the 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之外,什么都没有反序列化.

obj contains Items and Errors. And Items contains SubItems, but SubItems is null. So nothing except for Errors is actually getting deserialized.

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

It should be simple, but for some reason I can't figure out the correct object representation

对于"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"会因响应而异,并以字典键的形式读取这些名称.

This assumes that the item names "Item322A" and "Item2B" will vary from response to response, and reads these names in as the dictionary keys.

示例小提琴.