【发布时间】:2017-11-08 19:22:12
【问题描述】:
我知道如何反序列化基本的 Json 对象。我遇到了嵌套对象的问题;例如,这是我要反序列化的示例 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"
}
现在"data" 有未知数量的对象,可能是 100 可能是 1000 或者可能只是 1 并且它们都具有不同的名称。我的最终目标是获取数据中每个对象的信息。
我尝试了基本的 json 但根本没有用。
无论如何,这就是我尝试过的......
我创建了一个名为 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 的类
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; }
}
在我的驱动程序应用程序中我这样做了
string downloadedData = w.DownloadString(link);
test t = JsonConvert.DeserializeObject<test>(downloadedData);
但这并没有像我预期的那样工作。 任何帮助将不胜感激。
【问题讨论】:
-
在测试类中 public Dictionary
数据怎么样。而不是 List - >
-
您可以从 Visual Studio 中的 JSON 代码生成 JSON 类。选择您的 JSON 代码,将其复制到剪贴板,然后转到
EDIT -> PASTE SPECIAL -> JSON TO CLASSES。然后就可以使用生成的类进行反序列化了。 -
@Michael 虽然这是一个很好的提示,但它不适用于本示例。
-
@SamMarion 谢谢!我使用字典让它工作。
-
@Michael 感谢您的提示,我也查看了它,它很棒,但就像 SamMarion 所说,这不是我在此示例中要寻找的,但谢谢!
标签: c# json serialization json.net