Oct 13, 2011 at 1:20 PM
Edited Oct 13, 2011 at 2:59 PM
I'm evaluating the Web API for use in implementing our forthcoming REST service. Other contenders are WCF 4.0 and plain MVC 3.
Working on formatting my model classes for XML and JSON this morning, I found that the default use of the DataContractSerializer for JSON and the XmlSerializer for XML is wonderfully granular, but results in some ugly- and confusing- looking model classes.
You have to apply one attribute for XML and another for JSON (e.g. on properties). Every class needs a [DataContract] attribute, but not every class needs an [XmlType] attribute. The differing opt-in behaviours means that [XmlIgnore] has to be
applied to a non-serialized member, while a [DataMember] must NOT be applied. The result is a mess.
Using the DataContractSerializer for XML solves all this; the resulting model classes look nice and consistent. And at least it's easy to switch to the DCS:-
var config = new HttpConfiguration ();
config.Formatters.XmlFormatter.UseDataContractSerializer = true;
However, I would argue that the DCS should be the default for XML, and the more granular but more ugly option of using the XmlSerializer should have to be explicitly turned on by the Web API user.
My two cents...
**UPDATE** After reading SiggiG's comments in a related post today, I guess the current defaults should remain as-is if most people tend to use different casing for the names of the same JSON properties vs XML elements. Not something I do, being
a lower-case person.