Can you extend the default JsonConverter used in JSON.NET for collections?

Mark A. Donohoe picture Mark A. Donohoe · May 4, 2011 · Viewed 9.3k times · Source

I'm trying to write a custom JsonConverter for cases where a person subclasses a list or collection, but then adds extra properties to the subclass (see here). The current implementation of JSON.NET just changes the list into an array of child objects and ignores all of the added properties. So I want to write a new JsonConverter that treats the object as if it wasn't a List and to just serialize everything else as normal, but then to add a new property in the serialization called '_Items' where the actual array of data is stored.

Now I've already written a class that does exactly this for our specific List subclass, but I had to manually specify all the properties one-by-one. But if I could write a converter that treats this just as a normal object, then manually handle the items, I'd be golden. I don't even care if I end up duplicating half of another class (or even more!) but I'd love to make a reusable converter for these cases. However, as I said, I can't find the default converter to start from.

So... anyone know where that is?

Answer

jdknight picture jdknight · Sep 11, 2013

There is no 'default converter' in JSON.NET.

If you are able to examine the JsonSerializerInternalWriter class, look at the SerializeValue method. In it, there is the 'converter find and perform' phase at the top. However, if there is no converter that matches, it resorts to the contract type serialization (the switch statement).

I haven't found a way (a correct way or a graceful hack) to be able to perform a generic contract serialization (ex: parsing an object as normal) with an extended custom serialization on an entity (which I assume you are trying to do).