Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Order Matter in the XML Read by the DataContractSerializer?

I have the following code:

[DataContract(Namespace = "")]
public class User
{
    [DataMember]
    public string UserName { get; set; }

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

//Deserialization test
public void Test()
{

  //CASE 1.
  //string xml = "<User><UserName>john</UserName>" + 
  //                    "<FullName>John Lennon</FullName></User>";

  //CASE 2.
  string xml = "<User><FullName>John Lennon</FullName>" + 
                      "<UserName>john</UserName></User>";


  byte[] byteArray = Encoding.UTF8.GetBytes(xml);
  User user = null;
  using (MemoryStream stream = new MemoryStream(byteArray))
  {
    DataContractSerializer serializer = 
           new DataContractSerializer(typeof(User), "User", "");
    user = (User)serializer.ReadObject(stream);
  }
}

In case 1, FullName property isn't deserialized, but in case 2 it is deserialized properly. Why?

like image 328
synergetic Avatar asked Feb 12 '10 06:02

synergetic


1 Answers

Because order is significant. Alphabetic order is used unless you specify the order in your DataMember attributes.

This is explained in this MSDN article.

In general, it's a good practice to always explicitly specify Order on your DataMember attributes:

[DataMember(IsRequired=true, Order=0)]
public string FullName { get; set; }

[DataMember(IsRequired=true, Order=1)]
public string UserName { get; set; }
like image 90
Joe Avatar answered Sep 17 '22 21:09

Joe