[英]Deserialize complex JSON object using c#
我知道如何反序列化基本的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,但根本沒有用。
無論如何,這就是我嘗試過的...
我做了一個叫做數據的課
public class data
{
public long id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
}
然后我做了另一個叫做測試的課
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 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; }
}
這表明讀取對象是有效的:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.