简体   繁体   English

将JSON反序列化为C#列表

[英]Deserialize JSON into C# List

I am trying to deserialize JSON string into C# list. 我正在尝试将JSON字符串反序列化为C#列表。

The string looks like this: 该字符串如下所示:

{
    "object": {
        "key1":"",
        "key2":""
    },
    "someOtherObject": {
        "key1":"",
    },
    "anotherObject": {
        "key1":"",
        "key2":""
    }
}

I have tried using JsonConvert.DeserializeObject for this but it will not work since each of the objects has different name. 我尝试为此使用JsonConvert.DeserializeObject ,但由于每个对象都有不同的名称,因此它将无法工作。

What would be the workaround for this so object name would be stored maybe as another key? 解决此问题的办法是什么,以便将对象名称存储为另一个关键字?

From what I have found, I could create object class, someOtherObject class and anotherObject class and specify their fields as well as getters and setters, which would not be a problem if only I did not have 100+ such classes to create and their structure (fields) remains the same. 根据我的发现,我可以创建对象类,someOtherObject类和anotherObject类,并指定它们的字段以及getter和setter,如果仅我没有要创建的100多个此类及其结构,那么这将不是问题(字段)保持不变。

You can use Dictionary 您可以使用Dictionary

var dict = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(json);

if your keys are always key1 and key2 you can also use a temp class like 如果您的键始终是key1key2 ,则还可以使用一个临时类,例如

public class DummyClass
{
    public string Key1 { set; get; }
    public string Key2 { set; get; }
}

var dict2 = JsonConvert.DeserializeObject<Dictionary<string,DummyClass>>(DATA);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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