首页 文章

使用字典反序列化复杂的json对象

提问于
浏览
0

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

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对象(例如{“名称“:”值“})正确反序列化 . 要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList),例如List从JSON数组反序列化 . JsonArrayAttribute也可以添加到类型中以强制它从JSON数组反序列化 .

1 回答

  • 1

    其实很简单,使用方法:

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

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

相关问题