I am using Json.NET (6.0.3) for serialization. I wrote a custom JsonConverter TestConverter
that handles instances of some BaseClass
(by converting them to an integer id and back). Everything is working fine when I annotate the properties in my classes with JsonConverter[typeof(TestConverter)]
.
I would however very much prefer to use a custom contract resolver instead, which should, according to the documentation, be able to fully replace all attribute usage.
Here's how I set up the contract resolver:
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (typeof(BaseClass).IsAssignableFrom(property.PropertyType))
{
property.Converter = new TestConverter();
}
return property;
}
Everything is working fine for serialization, however it seems that the converter I set up in the contract resolver are completely ignored during the deserialization process. The ReadJson
method of TestConverter
is never called.
Am I missing something really obvious? Do I need to attach the converter to property in some other place?
I created a small runable example that demonstrates the problem. If the [JsonConverter]
attribute in line 57 is commented out, the program will crash with an exception because Json.net is trying to convert an integer to an object instead of using the TestConverter
.
The source for the example can be found here: http://pastebin.com/xgVS6hXY
Thank you in advance for any help!
Remove the [JsonConverter(typeof(TestConverter))]
attribute from the Artist property of Song
class. Change the setup of the contract resolver to the following sample:
public class TestContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (typeof(BaseClass).IsAssignableFrom(property.PropertyType))
{
var converter = new TestConverter();
property.Converter = converter;
property.MemberConverter = converter;
}
return property;
}
}
Everything should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With