问题
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