Search code examples
c#jsonjson.netdeserializationjson-deserialization

Parse json that have uncertain number of data


How to parse json that have the Assets object is unknown?

As

{   
    "ClassName": "Excel",
    "Teacher": "Esther",
    "Student": 50,
    "Aircond": 0,
    "Assets": {
        "Chair": 50,
        "Table": 50,
        "Fan": 2,
        and might be more here and is unknown to me
    }
}

Solution

  • You can use dynamic as Assets type:

    public class RootObject
    {
        public string ClassName { get; set; }
        public string Teacher { get; set; }
        public int Student { get; set; }
        public int Aircond { get; set; }
        public dynamic Assets { get; set; }
    }
    

    And then

    RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);