Who doesn’t like mixing their Raisin Flakes with their Oaty-O’s in the morning? Yum! But it’s not a good idea if you’re talking about serial formats in C# 3.5 instead of breakfast cereals. You’ll get output that might leave a bad taste in your mouth.
Question: You’re writing a web API for an application. To give developers the most flexibility in interacting with your system, you want to expose classes that can be serialized to either XML or JSON. Using WCF and C# 3.5 SP1, what are your options?
Answer: There’s only one option unless you rely on 3rd party serialization libraries. You must mark the class with the
[DataContract] attribute and mark each serializable member with
[DataMember]. This allows you to serialize and deserialize using the DataContractSerializer and DataContractJsonSerializer for XML and JSON respectively.
I mention this because we’d gone to great lengths to customize our XML using the IXmlSerializable interface. This gave us fine control over the properties we wanted to appear in our XML output and how they were formatted. But if you use the
IXmlSerializable interface, you can’t also annotate the class with the
[DataContract] attribute. You’ll get a compiler error. Sowmy Srinivasan explains this serialization restriction.
I know what you’re thinking: If the framework provides an
IXmlSerializable interface, isn’t there also an
IJsonSerializable interface? Sadly, no. There’s no way to fine-tune the JSON output. Sigh.
So, if you’re currently using
IXmlSerializable, you can forget about the
DataContractJsonSerializer. Or you can accept that you’re fighting the framework, forget about your fancy-pants XML format, and accept the default serialization, keeping these data member best practices in mind.
Infovark has too much invested in our XML layout at this point. We’ve built our XSD files, XSL Transforms, and many, many unit tests. So we gave up on the
DataContractJsonSerializer and turned to the excellent JSON.NET, written by James Newton-King. It’s now version 3.0 and fully supports the new LINQ constructs.
It’s a little more work, but we think it’s worth it.