7

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.

rogueg
  • 293
  • 3
  • 10

4 Answers4

4

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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

Morbia
  • 4,144
  • 3
  • 21
  • 13
1

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.

The_Ghost
  • 2,070
  • 15
  • 26
  • Link is broken. – Paul Tsai May 23 '17 at 15:19
  • 1
    This link works: http://web.archive.org/web/20130430190551/http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/ ...from this answer: https://stackoverflow.com/a/2505801/530545 – Granger Mar 08 '19 at 20:49
0

you can uses ScriptIgnore attribute as mentioned here:- Ignoring a field during .NET JSON serialization; similar to [XmlIgnore]? Though I am looking forward to implement something like you want, don't want to decorate lot of nested objects

Community
  • 1
  • 1
Anand
  • 4,523
  • 10
  • 47
  • 72