简体   繁体   中英

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.

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

First create a temporary class to read the Json,

// New temporary class
    public class TempClass
    {
        public List<ItemClass> ItemList { get; set; }
        public ListInfo ListInfo { get; set; }
    }

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

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

Above temp-class will hold the de-serialized object. Then use the following way to de-serialize and read the two different objects.

List<ItemClass> ItemsList = ((TempClass)JsonConvert.DeserializeObject<TempClass>(strJsom, new JsonSerializerSettings())).ItemList;
ListInfo ListInfo = ((TempClass)JsonConvert.DeserializeObject<TempClass>(strJsom, new JsonSerializerSettings())).ListInfo;

Now, you can traverse through the ItemsList to read each ItemClass from the Json.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM