无法将JSON序列化为字典

时间:2018-04-11 19:29:29

标签: c# json dictionary json.net yamldotnet

我在使用字典属性的类中遇到了JSON序列化的问题 整个过程有点复杂,作为输入我有一个YAML文件,我使用YamlDotNetNewtonSoft like so

转换为json

这是Yaml和JSON输出的示例

some_element: '1'
should_be_dic_element:
 - a: '1'
 - b: '2'

{
 "some_element": "1",
 "should_be_dic_element": [
  {
   "a": "1"
  },
  {
   "b": "2"
  }
 ]
}

和班级

 public class SomeClass
 {
    [JsonProperty(PropertyName = "some_element")]
    public string SomeProperty { get; set; }

    [JsonProperty(PropertyName = "should_be_dic_element")]
    public Dictionary<string, string> Dictionary { get; set; }
 }

我知道Array字典的问题所以这就是我尝试过的所有事情。

使用词典我得到以下

  

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

使用Dictionary中的新类,如此

[JsonArray]
class X : Dictionary<string, string> { }
  

错误值不能为空。   参数名称:key

使用KeyValuePair<string, string>[] / List<KeyValuePair<string, string>>结果是元素的数量,但值为空。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

我认为您尝试反序列化的JSON不符合您的类定义。尝试更改生成JSON的方式。

对于字典类型的结构,我希望看到花括号{而不是[来开始结构,例如:

{
 "some_element": "1",
 "should_be_dic_element": {
  {
   "a": "1"
  },
  {
   "b": "2"
  }
 }
}

如果要对现有JSON进行反序列化,请尝试使用类定义来指定字典列表:

 public class SomeClass
 {
    [JsonProperty(PropertyName = "some_element")]
    public string SomeProperty { get; set; }

    [JsonProperty(PropertyName = "should_be_dic_element")]
    public List<Dictionary<string, string>> Dictionary { get; set; }
 }