[Solved] Deserialize nested JSON into C# class


Your data model should be as follows:

public class Info
{
    public string prop1 {get;set;}
    public string prop2 {get;set;}
    public int prop3 {get;set;}
    // Modified from 
    //public Dictionary<string, List<int>> prop4 {get;set}
    public List<Dictionary<string, int>> prop4 {get;set;}
}

public class Response
{
    // Modified from 
    //public class Dictionary<string, List<Info>> Item {get;set;}
    public Dictionary<string, Info> Items {get;set;}
}

Notes:

  • Response.Item should have been named Items.

  • In your JSON, "Items" is an object with variably-named object-valued properties:

    {
        "Items": {
            "Item_1A": { },
            "Item2B": { }
        }
    }
    

    This should be modeled as a Dictionary<string, T> for an appropriate non-collection type T. Assuming you are using json.net see Serialization Guide: Dictionaries for details. If not, javascriptserializer behaves similarly.

    Your data model, public class Dictionary<string, List<Info>> Items, would have been appropriate for an object with variably-named array-valued properties:

    {
        "Items": {
            "Item_1A": [{ },{ }],
            "Item2B": [{ }]
        }
    }
    

    But this is not what you have.

  • Meanwhile "prop4" is an array containing object with variably-named object-valued properties such as:

    "prop4": [ // Outer container is an array
      {        // Inner container is an object
        "prop_x": 100
      },
      {
        "prop_y": 200
      }
    ]
    

    Thus a collection such as List<T> should be used as the outer generic type:

    public List<Dictionary<string, int>> prop4 {get;set;}
    

    See Serialization Guide: IEnumerable, Lists, and Arrays.

  • As you have noticed, code-generation tools such as those mentioned in How to auto-generate a C# class file from a JSON object string generally cannot recognize JSON objects with variable property names. In such a situation an auto-generated class may need to get manually replaced with an appropriate Dictionary<string, T> property in the containing type.

Sample working fiddle here.

0

solved Deserialize nested JSON into C# class