本文介紹了如何反序列化具有動(dòng)態(tài)(數(shù)字)鍵名的子對(duì)象?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
如何反序列化此 JSON 數(shù)據(jù)?100034"等鍵本質(zhì)上是動(dòng)態(tài)的.
How can I deserialize this JSON data? The keys "100034" etc. are dynamic in nature.
{
"users" : {
"100034" : {
"name" : "tom",
"state" : "WA",
"id" : "cedf-c56f-18a4-4b1"
},
"10045" : {
"name" : "steve",
"state" : "NY",
"id" : "ebb2-92bf-3062-7774"
},
"12345" : {
"name" : "mike",
"state" : "MA",
"id" : "fb60-b34f-6dc8-aaf7"
}
}
}
有沒(méi)有一種方法可以直接訪問(wèn)具有名稱、狀態(tài)和 ID 的每個(gè)對(duì)象?
Is there a way I can directly access each object having name, state and Id?
推薦答案
對(duì)于屬性名稱可變的 JSON 對(duì)象,您可以使用 Dictionary
代替常規(guī)類,其中 T
是表示項(xiàng)目數(shù)據(jù)的類.
For JSON objects having property names which can vary, you can use a Dictionary<string, T>
in place of a regular class, where T
is a class representing the item data.
像這樣聲明你的類:
class RootObject
{
public Dictionary<string, User> users { get; set; }
}
class User
{
public string name { get; set; }
public string state { get; set; }
public string id { get; set; }
}
然后像這樣反序列化:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
演示:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""users"": {
""10045"": {
""name"": ""steve"",
""state"": ""NY"",
""id"": ""ebb2-92bf-3062-7774""
},
""12345"": {
""name"": ""mike"",
""state"": ""MA"",
""id"": ""fb60-b34f-6dc8-aaf7""
},
""100034"": {
""name"": ""tom"",
""state"": ""WA"",
""id"": ""cedf-c56f-18a4-4b1""
}
}
}";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (string key in root.users.Keys)
{
Console.WriteLine("key: " + key);
User user = root.users[key];
Console.WriteLine("name: " + user.name);
Console.WriteLine("state: " + user.state);
Console.WriteLine("id: " + user.id);
Console.WriteLine();
}
}
}
輸出:
key: 10045
name: steve
state: NY
id: ebb2-92bf-3062-7774
key: 12345
name: mike
state: MA
id: fb60-b34f-6dc8-aaf7
key: 100034
name: tom
state: WA
id: cedf-c56f-18a4-4b1
這篇關(guān)于如何反序列化具有動(dòng)態(tài)(數(shù)字)鍵名的子對(duì)象?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!