使用c#反序列化复杂的JSON对象

Muh*_*mah 0 c# serialization json json.net

我知道如何反序列化基本的Json对象.我遇到嵌套对象的问题; 例如,这是一个我想要反序列化的例子.

{
    "data": {
        "A": {
            "id": 24,
            "key": "key",
            "name": "name",
            "title": "title"
        },
        "B": {
            "id": 37,
            "key": "key",
            "name": "name",
            "title": "title"
        },
        "C": {
            "id": 18,
            "key": "key",
            "name": "name",
            "title": "title"
        },
        "D": {
            "id": 110,
            "key": "key",
            "name": "name",
            "title": "title"
        }
      },
    "type": "type",
    "version": "1.0.0"
}
Run Code Online (Sandbox Code Playgroud)

现在"data"有一个未知数量的对象,可能是100可能是1000或可能只有1,所有这些对象都有不同的名称.我的最终目标是获取数据中每个对象的信息.

我试过基本的json,但根本没用.

无论如何,这是我试过的......

我做了一个叫做数据的课

public class data
{
    public long id { get; set; }
    public string key { get; set; }
    public string name { get; set; }
    public string title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我做了另一个名为test的课程

public class test
{
    /*
    I have also tried this, which works but then I don't know what to do with it and how to deserialize the information of it.
    //public Newtonsoft.Json.Linq.JContainer data { get; set; }
    */
    public List<List<data>> data { get; set; }
    public string type { get; set; }
    public string version { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的驱动程序应用程序中,我这样做了

 string downloadedData = w.DownloadString(link);
 test t = JsonConvert.DeserializeObject<test>(downloadedData);
Run Code Online (Sandbox Code Playgroud)

但这并没有像我预期的那样奏效.任何帮助,将不胜感激.

Com*_*eak 6

你正在寻找一本字典.

使用此作为您的类定义:

public class Rootobject
    {
        public Dictionary<string, DataObject> data { get; set; }
        public string type { get; set; }
        public string version { get; set; }
    }
    public class DataObject
    {
        public int id { get; set; }
        public string key { get; set; }
        public string name { get; set; }
        public string title { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

这表明阅读您的对象有效:

var vals = @"{

""data"": {
    ""A"": {
        ""id"": 24,
        ""key"": ""key"",
        ""name"": ""name"",
        ""title"": ""title""
    },
    ""B"": {
        ""id"": 37,
        ""key"": ""key"",
        ""name"": ""name"",
        ""title"": ""title""
    },
    ""C"": {
        ""id"": 18,
        ""key"": ""key"",
        ""name"": ""name"",
        ""title"": ""title""
    },
    ""D"": {
        ""id"": 110,
        ""key"": ""key"",
        ""name"": ""name"",
        ""title"": ""title""
    }
  },
""type"": ""type"",
""version"": ""1.0.0""
}";
var obj = JsonConvert.DeserializeObject<Rootobject>(vals);
Run Code Online (Sandbox Code Playgroud)