torsdag 29 november 2007

DataContractSerializer requires alphabetic element order

When using the DataContractSerializer to deserialize objects either from pure XML or implicit using WCF it requires the XML elements to appear in alphatic order.

Let says we have the following class:
[DataContract]public class auth
{
[DataMember]
public string username;
[DataMember]
public string password;
}

...and the following XML input:
<auth>
<username>ABC</username>
<password>DEF</password>
</auth>

Using this XML, the DataContractSerializer would deserialize the "Auth" class and Username property correctly - but the Password property would be null.

The reason is that the DataContractSerializer requires the element order in the XML to be in alphabetic order, ie:
<auth>
<password>DEF</password>
<username>ABC</username>
</auth>


The sort order can be set explicitly using the "Order" property on the "DataMember" attribute - however: it would still require the XML input to follow a specific order.
Example using the "Order" property and allowing the username element to appear before the password element:
[DataContract]
public class auth
{
[DataMember(Order=1)]
public string username;
[DataMember(Order=2)]
public string password;
}



Inga kommentarer: