将JSON数组反序列化为对象
本文关键字:对象 反序列化 数组 JSON | 更新日期: 2023-09-27 18:27:30
我已经开始做这件事有一段时间了,似乎无法完全理解,本质上我有一个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);