使用C#反序列化复杂的JSON对象 [英] Deserialize complex JSON object using c#
问题描述
我知道如何反序列化基本Json对象.我对嵌套对象有疑问;例如,这是我要反序列化的json示例.
I know how to deserialize basic Json object. I am having a problem with nested objects; for example, here is an example json i want to deserialize.
{
"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"
}
现在"data"
具有未知数量的对象,可以是100,可以是1000或可以只是1,并且所有这些都具有不同的名称.我的最终目标是获取数据中每个对象的信息.
Now "data"
has an unknown number of objects, could be 100 could be 1000 or could be just 1 and all of them with different name. My ultimate goal is to get the information of each object inside data.
我尝试了基本的json,但根本没有用.
I tried basic json but didn't work at all.
无论如何,这就是我尝试过的...
Anyways, this is what I have tried...
我创建了一个名为data的类
I made class called data
public class data
{
public long id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
}
然后我做了另一个叫做test的课
then I made another class called 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; }
}
在我的驱动程序应用程序中,我做到了
and in my driver application I did this
string downloadedData = w.DownloadString(link);
test t = JsonConvert.DeserializeObject<test>(downloadedData);
但是,这没有达到我的预期. 任何帮助将不胜感激.
But this didn't work as I expected to. Any help would be appreciated.
推荐答案
您正在寻找字典.
使用它作为您的类定义:
Use this as your class definition:
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; }
}
这表明读取对象是可行的:
And this demonstrates that reading your object works:
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);
这篇关于使用C#反序列化复杂的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!