如何反序列化具有多个不同类型对象的 JSON 字符串

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

我有以下 json 字符串:"{"\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],"listInfo":{"info1":1,"info2":"bla"}}"

我有以下 类:

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

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

如何将我的 json 字符串反序列化为它包含的两个不同对象,ItemListListInfoItemList 应该反序列化为 List<ItemClass>。我使用 JsonConvert 多次使用反序列化,但使用 json 字符串表示单个对象。

您的 json 格式不正确。更改 "{"\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],"listInfo":{"info1":1,"info2":"bla"}}"

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

然后像这样创建一个class

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

并使用 JsonConvert.DeserializeObject 将 json 反序列化为您的 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);

首先创建一个临时的class来读取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 将保存反序列化的对象。然后使用下面的方式反序列化读取两个不同的对象。

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

现在,您可以遍历 ItemsList 以读取 Json 中的每个 ItemClass

希望对您有所帮助。