【问题标题】:Deserializing complex json object with dictionary用字典反序列化复杂的json对象
【发布时间】:2013-06-22 12:06:15
【问题描述】:

我正在使用 Newtonsoft Json.Net 将 json 输入反序列化为对象:

json:

staticKey1: value,
staticKey2: value,

results: [
{
   key1: value1,
   key2: value2,
   key3: value3,
...
   keyN: valueN
}
],

C#类:

public class MyClassName
{
    public string staticKey1 { get; set; }
    public string staticKey2 { get; set; }
    public Dictionary<String, String> results { get; set; }
}

我正在使用 Newtonsoft.Json.JsonConvert.DeserializeObject(),但出现异常:

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'System.Collections.Generic.Dictionary`2[System.String,System.String]' 因为该类型需要一个 JSON 对象(例如 {"name":"value"}) 正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为 实现集合接口的数组或类型(例如 ICollection, IList) 之类的可以从 JSON 反序列化的 List 大批。 JsonArrayAttribute 也可以添加到类型中以强制它 从 JSON 数组反序列化。

【问题讨论】:

    标签: silverlight c#-4.0 json.net deserialization


    【解决方案1】:

    其实很简单,使用:

    public class MyClass
    {
        public string staticKey1 { get; set; }
        public string staticKey2 { get; set; }
        public IEnumerable<IDictionary<string, string>> results { get; set; }
    }
    

    但也许有更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      相关资源
      最近更新 更多