Deserialize JSON dictionary values with JsonConverter

空扰寡人 提交于 2019-12-20 03:29:26

问题


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?


回答1:


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);



回答2:


Add the attribute to your Foo class. This is probably because your Dictionary could contain two different types and the attribute would not know which one you are referring to.

[JsonDictionary(ItemConverterType = typeof(FooJsonConverter))]
public class Foo
{

    ...

}


来源:https://stackoverflow.com/questions/33674734/deserialize-json-dictionary-values-with-jsonconverter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!