Archives For July 2013

I have been using .NET and WCF for quite a while now and I’ve become quite accustom to writing classes as follows.


[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}

I am a big fan of ReSharper and I usually make a rule of following their naming conventions which means camel case class names and camel case public property names both with the first letter being uppercase. The problem was that I was needing to encode some classes using DataContractJsonSerializer and my reason for encoding them was to send them over the wire to an api that expected the JSON to look as follows.


{
    "firstName": "Brian",
    "lastName": "Jones"
}

Of course the problem was that the class as written above would instead encode the keys with an uppercase first letter. Also the api I was consuming did not require all of the fields to be present in the JSON, but did expect them to be strings if they were supplied and not to be set to null. In order to address both issues I was able to set two properties on the DataMember attribute. The properties were ‘Name’ and ‘EmitDefaultValue’. The ‘Name’ property will use the supplied string in place of the property name when encoding the class. Setting the ‘EmitDefaultValue’ property to ‘false’ will prevent the property from being serialized if it is null.


[DataContract]
public class Person
{
    [DataMember(Name = "firstName", EmitDefaultValue = false)]
    public string FirstName { get; set; }

    [DataMember(Name = "lastName", EmitDefaultValue = false)]
    public string LastName { get; set; }
}

There are also two other properties that can be set for DataMember, ‘IsRequired’ and ‘Order’. Setting ‘IsRequired’ to true will cause the serializer to ensure that the field is present when deserializing JSON data. If the field is not present then it will throw a SerializationException.

Setting the ‘Order’ property has some gotchas. As you would assume it can be used to specify the order in which elements will be serialized. The gotcha is that if there are properties that do not specify an order they are by default serialized first. The second gotcha is that elements in base classes will also be serialized first. So when using order I would recommend it being all or nothing. Either specify it for every property, or don’t specify it at all.