[英]Iterating over a JSON object (NOT an array) in C#
所以,我有一個以下格式的json文件
{
"-KeArK3V02mXYWx2OMWh" : {
"Description" : "this is a description",
"Location" : "Atlanta",
"Name" : "Event One",
"Time" : "2017-03-01T21:53:12.924645Z"
},
"-KeAtCNF_rmewZ_U3PpH" : {
"Description" : "another description",
"Location" : "Charlotte",
"Name" : "Event Two",
"Time" : "2017-03-01T22:01:25.603547Z"
},
"-KeAtd8CQW_EfH3Sw4YQ" : {
"Description" : "description goes here",
"Location" : "Toronto",
"Name" : "Event Three",
"Time" : "2017-03-01T22:03:19.3953859Z"
}
}
我有一個名為 Event 的類,其定義如下
class Event {
public string Description { get; set; }
public string Location { get; set; }
public string Name { get; set; }
public DateTime Time { get; set; }
}
我想通過這個並將每個子節點反序列化為事件對象,基本上將整個 JSON 反序列化為 List<Event>。
問題是事件不在數組中,它們是另一個 JSON 對象的子節點。 所以事實證明它不是那么簡單
List<Event> elist = JsonConvert.DeserializeObject<List<Event>>(jsonResult);
我看到過類似的問題,詢問項目在 JSON 數組中的組織位置,我嘗試了那里列出的解決方案,但它們僅在實際數組時才有效,而不是我在這里的結構。 我在這里使用的是 Google Firebase,不幸的是它不支持 JSON 數組,因此我無法將這些項目包含在數組中。
我不太習慣 JSON 語法,所以我可能在這里遺漏了一些非常明顯的東西,但我完全被難住了。
任何幫助將不勝感激。
你能試試這個方法嗎? 這很直接
var str = @"{
'-KeArK3V02mXYWx2OMWh' : {
'Description' : 'this is a description',
'Location' : 'Atlanta',
'Name' : 'Event One',
'Time' : '2017-03-01T21:53:12.924645Z'
},
'-KeAtCNF_rmewZ_U3PpH' : {
'Description' : 'another description',
'Location' : 'Charlotte',
'Name' : 'Event Two',
'Time' : '2017-03-01T22:01:25.603547Z'
},
'-KeAtd8CQW_EfH3Sw4YQ' : {
'Description' : 'description goes here',
'Location' : 'Toronto',
'Name' : 'Event Three',
'Time' : '2017-03-01T22:03:19.3953859Z'
}
}";
Dictionary<string, Event> elist = JsonConvert.DeserializeObject<Dictionary<string, Event>>(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.