Friday 14 September 2012

DataContract attribute gotcha

A little known fact that has caught out a few of our project team members this week, including myself. If you annotate a class with the DataContract attribute, then you must also ensure that the members you want to have serialized are also annotated with the DataMember / EnumMember attribute as well. The ones that aren't annotated will NOT get de-serialized when the data arrives at the consumer of your service method.

Note: If you apply no DataContract annotation at all to the class, then this has the same affect of attributing every member in your class with the DataMember / EnumMember attribute.

To be fair, this is somewhat eluded to in the following Microsoft article, although the part about it being implicit if you don't apply the attribute is not entirely obvious at first...

image

Silverlight 5 also supports a simplified opt-out model for serialization, where these attributes can be omitted from the type and the members of the type to be serialized. The data contract is implicit in the sense that the visibility modifiers (public, private) used by the type determines whether it and its members are included in the data contract. In this model, the name of a member is used to identify it in the serialized representation. A new IgnoreDataMemberAttribute attribute can be used to opt-out a member that is public when required.

No comments:

Post a Comment

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...