Search code examples
c#jsonjson.netdeserializationjson-deserialization

Deserialize nested JSON into C# objects


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"]
}

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; }
    }

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 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


Solution

  • For "Items" use a Dictionary<string, List<Info>>, i.e.:

    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; }
    }
    

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

    Sample fiddle.