Peter Goodman bio photo

Peter Goodman

A developer living in Auckland building software using all sorts of bits and pieces I find along the way. Originally from Northern Ireland.

Twitter Google+ LinkedIn Github

Previously I posted about the problem with WCF and collection which have a payload in them. I came across this problem again when using the DataContractJsonSerializer and thought I would look at possibilities to resolve it.

If you have implemented the IXmlSerializable interface then you are kind of stuffed because the Json serializer will emit json with a bunch of xml in the middle….nice! It is really useful to reference sowmy’s post on the precedence of serializable classes in the Data Contract family of serializers.

Instead you can use a Surrogate. This is a class which implements IDataContractSurrogate and can be passed to the constructor of the serializer. It tells the serializer that when you come to serialize type x, instead use type y and I will give you the converted instance. At the other end the class gets deserialized into the original type and all is good.

For our custom collection with payload this works great. It will not however work with CLR types like DateTime, the precedence of WCF serialization kicks in before the surrogate provider is queried for a transmission type.