与JsonConverter反序列化JSON字典中的值 [英] Deserialize JSON dictionary values with JsonConverter

查看:746
本文介绍了与JsonConverter反序列化JSON字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Json.NET库进行反序列化JSON。对于一个抽象类我有一个自定义的 JsonConverter 。这是我用它的方式:



<预类=郎CSHARP prettyprint-覆盖> [JsonConverter(typeof运算(FooJsonConverter))]
酒店的公共富MyFoo {搞定;组; }



到目前为止好。当我在字典使用Foo类的问题出现了。这是我尝试:



<预类=郎CSHARP prettyprint-覆盖> [JsonDictionary(ItemConverterType = typeof运算(FooJsonConverter))]
酒店的公共字典<字符串,富> MyFooDictionary {搞定;组; }



但上面给出了错误:



< BLOCKQUOTE>

属性JsonDictionary不在此声明类型有效。这是
只在类,接口声明有效。




如何指定字典值转换器?


解决方案

使用 [JsonProperty] 而不是 [JsonDictionary]

  [JsonProperty(ItemConverterType = typeof运算(FooJsonConverter))] 
公众解释<串,富> MyFooDictionary {搞定;组; }



小提琴:的 https://dotnetfiddle.net/QJCtBg



另一种方法是你的转换器添加到 JsonSerializerSettings 并传递给 JsonConvert.DeserializeObject

  VAR设置=新JsonSerializerSettings(); 
settings.Converters.Add(新FooJsonConverter());

VAR OBJ = JsonConvert.DeserializeObject<&OBJTYPE GT;(JSON,设置);


I use Json.NET library to deserialize JSON. For an abstract class Foo I have a custom JsonConverter. This is the way I have used it:

[JsonConverter(typeof(FooJsonConverter))]
public Foo MyFoo { get; set; }

So far so good. The problem arises when I use the Foo class in a Dictionary. This was my attempt:

[JsonDictionary(ItemConverterType = typeof(FooJsonConverter))]
public Dictionary<string, Foo> MyFooDictionary { get; set; }

But the above gives the error:

Attribute 'JsonDictionary' is not valid on this declaration type. It is only valid on 'class, interface' declarations.

How to specify converter for Dictionary value?

解决方案

Use [JsonProperty] instead of [JsonDictionary].

[JsonProperty(ItemConverterType = typeof(FooJsonConverter))]
public Dictionary<string, Foo> MyFooDictionary { get; set; }

Fiddle: https://dotnetfiddle.net/QJCtBg

Another alternative is to add your converter to the JsonSerializerSettings and pass that to JsonConvert.DeserializeObject.

var settings = new JsonSerializerSettings();
settings.Converters.Add(new FooJsonConverter());

var obj = JsonConvert.DeserializeObject<ObjType>(json, settings);

这篇关于与JsonConverter反序列化JSON字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆