将JSON数组反序列化为对象

时间:2014-10-23 13:15:12

标签: c# json

我已经开始使用了一段时间并且似乎无法理解它,基本上我有一个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"
  }
]

2 个答案:

答案 0 :(得分:2)

您应该将其反序列化为列表:

public IList<Notifications> Notes;

Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);

应该工作!

答案 1 :(得分:2)

您的调用尝试反序列化单个对象。这个对象的预期Json将是值的字典,这是错误消息所说的。

您应该尝试反序列化为IEnumerable派生的集合,例如数组或列表:

Notifications[] Notes = JsonConvert.DeserializeObject<Notifications[]>(responseString);

IList<Notifications> Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);