Search code examples
c#json-deserializationjsonconvert

How to deserialize a JSON string that has multilple objects of different type


I have the following json string: "{"\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],"listInfo":{"info1":1,"info2":"bla"}}"

I have the following classes:

class ItemClass
{
    public int Id;
    public string Name;
}

class ListInfo
{
    public int Info1 { get; set; }
    public string Info2 { get; set; }
}

How can I deserialize my json string into the two different objects it contains, ItemList and ListInfo? ItemList should be deserialized into a List<ItemClass>. I've used deserialization many times using JsonConvert but with a json string that represents a single object.


Solution

  • Your json format is incorrect. change the "{"\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],"listInfo":{"info1":1,"info2":"bla"}}"

    to

    "{\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],\"listInfo\":{\"info1\":1,\"info2\":\"bla\"}}"

    then create a class like this

    public class BaseClass
    {
        public List<ItemClass> ItemList { get; set; }
        public ListInfo ListInfo { get; set; }
    }
    

    and use JsonConvert.DeserializeObject to deserialize json to your class

    string json = "{\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],\"listInfo\":{\"info1\":1,\"info2\":\"bla\"}}";
    var data =  JsonConvert.DeserializeObject<BaseClass>(json);