【问题标题】:Deserialize JSON Array to object将 JSON 数组反序列化为对象
【发布时间】:2014-10-23 13:15:11
【问题描述】:

我已经开始研究了一段时间,但似乎无法完全理解它,本质上我有一个 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"
  }
]

【问题讨论】:

  • 可能是因为您的数组未命名,即它应该类似于 { "arrayname": [ {...}, {...} ] } ?
  • 需要反序列化为数组或集合

标签: c# json


【解决方案1】:

你应该将它反序列化为一个列表:

public IList<Notifications> Notes;

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

应该可以!

【讨论】:

  • 也可以是一个数组。
  • 呃,我不确定该选哪一个,他们都可以工作!
【解决方案2】:

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

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

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

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

【讨论】:

  • 我赞成这个,因为它也有效,Charles 之前就到过那里,虽然希望这看起来公平?
猜你喜欢
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多