Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF custom serializer

I'm creating a web service in WCF that returns JSON, but the DataContractJsonSerializer is balking on some circular references (which I can't remove in this particular case).

Instead, I'd like to use the Newtonsoft json library. What's the easiest way to create a custom serializer in WCF?

Note: I know I could just return a stream, but I don't want operation code aware of serialization stuff.

like image 968
rogueg Avatar asked Jun 08 '09 23:06

rogueg


3 Answers

Re pure WCF: if you control both ends of the wire (on "full" .NET), then applying a custom serializer is relatively simple - you add a behaviour inherited from DataContractSerializerOperationBehavior, and override CreateSerializer - see here (with attribute here).

However! My understanding (untested) is that a JSON-enabled WCF service won't use this route, but will apply its own serializer directly.

like image 139
Marc Gravell Avatar answered Nov 07 '22 09:11

Marc Gravell


Set IsReference attribute of DataContract to true, it is available with .NET 3.5SP1

[DataContract(IsReference = true)]
public class Employee

For more details see. MSDN DataContractAttribute.IsReference

like image 2
Morbia Avatar answered Nov 07 '22 09:11

Morbia


Very good article: XmlSerializer vs DataContractSerializer: Serialization in Wcf. There Dan Rigsby is showing different scenarios and how to make your own serializer in more detail.

like image 1
The_Ghost Avatar answered Nov 07 '22 09:11

The_Ghost