Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom JsonConverter is ignored for DEserialization when using custom contract resolver instead of JsonConverter attribute

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 ReadJsonmethod 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!

like image 736
Jonas Avatar asked Oct 01 '22 06:10

Jonas


1 Answers

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.

like image 115
Ilija Dimov Avatar answered Oct 05 '22 23:10

Ilija Dimov