Cannot deserialize an object using a converter?

259 Views Asked by At

Given a JSON string of the form {"$type":"MyType, MyAssembly","seed":0"}, why can't JsonConvert.DeserializeObject utilize the JsonConverter associated with "MyType"?

I've tried decorating the MyType class with a [JsonConverter(typeof(MyType))] attribute. Doesn't work. The custom JsonConverter's ReadJson method is never called.

I've tried adding the custom converter to the serializer's settings Converters collection and made sure the CanConvert method returns true for 'MyType' and the CanRead method returns true. Doesn't work. Neither the converter's CanConvert nor its ReadJson method is ever called.

The DeserializeObject method needs to be able to deserialize a JSON string containing an object whose type is unknown at compile time, but whose type is embedded in the JSON object via the special "$type" member. So don't suggest using DeserializeObject<T> or point out that it works for members, whose type is identified in the contract before hand.

FYI, this problem generalizes to cases where the deserialization needs to identify the object type solely from the embedded "$type" member, so for example, it also fails to resolve a converter if the JSON object is in an untyped JSON array, not just at the top-level.

Basically, an object cannot survive a round trip through the serialization/deserialization process, because although the WriteJson method will be called for the Converter when SerializeObject is called, when you subsequently pass the JSON string to DeserializeObject, it fails to call the converter's ReadJson method, and instead constructs an new instance and uses the basic member population routines.

0

There are 0 best solutions below