[英]Deserialize JSON Array to object
我已經開始有一段時間了,似乎還不太明白,基本上我有一個JSON數組,我想將其解碼為Notifications對象,但例外是:
“ Newtonsoft.Json.dll中發生了'Newtonsoft.Json.JsonSerializationException類型的未處理異常。附加信息:由於類型需要,因此無法將當前JSON數組(例如[1,2,3])反序列化為'WpfApplication2.Notifications'類型。 JSON對象(例如{“ name”:“ value”})以正確反序列化。”
public Notifications Notes;
// HTTP request gets the JSON below.
//EXCEPTION ON THIS LINE
Notes = JsonConvert.DeserializeObject<Notifications>(responseString);
public class Notifications
{
[JsonProperty("note_id")]
public int note_id { get; set;}
[JsonProperty("sender_id")]
public int sender_id { get; set; }
[JsonProperty("receiver_id")]
public int receiver_id { get; set; }
[JsonProperty("document_id")]
public int document_id { get; set; }
[JsonProperty("search_name")]
public string search_name { get; set; }
[JsonProperty("unread")]
public int unread { get; set; }
}
檢索到的Json是:
[
{
"note_id": "5",
"sender_id": "3",
"receiver_id": "1",
"document_id": "102",
"unread": "1"
},
{
"note_id": "4",
"sender_id": "2",
"receiver_id": "1",
"document_id": "101",
"unread": "1"
}
]
您應該將其反序列化為列表:
public IList<Notifications> Notes;
Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);
應該管用!
您的呼叫嘗試反序列化單個對象。 對於這樣的對象,期望的Json將是值的字典,這就是錯誤消息在說什么。
您應該嘗試反序列化為IEnumerable派生的集合,例如數組或列表:
Notifications[] Notes = JsonConvert.DeserializeObject<Notifications[]>(responseString);
要么
IList<Notifications> Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.