Monday, May 16, 2016

Deserializing XML in .NET

At first glance it seems reasonable that the following XML would be nicely deserialized into the .NET class below.
<?xml version="1.0" encoding="UTF-8"?>
<GetTicketHTTPResponse>
    <ticket>b99a2231-c0a8-0c21-7dd8-76fde0745043</ticket>
    <expires>1463445966897</expires>
    <userid>30269422</userid>
</GetTicketHTTPResponse>
[DataContract(Name = "GetTicketHTTPResponse")]
public class GetTicketHTTPResponse
{
    [DataMember(Name = "ticket")]
    public string Ticket { get; set; }

    [DataMember(Name = "expires")]
    public string Expires { get; set; }

    [DataMember(Name = "userid")]
    public string UserId { get; set; }
}
But NO, it will NOT. The .NET DataContractSerializer assumes that the XML elements appear in alphabetical order and since they do not the expires element will be ignored. The following slightly changed code though will save the day.
[DataContract(Name = "GetTicketHTTPResponse")]
public class GetTicketHTTPResponse
{
    [DataMember(Name = "ticket", Order = 1)]
    public string Ticket { get; set; }

    [DataMember(Name = "expires", Order = 2)]
    public string Expires { get; set; }

    [DataMember(Name = "userid", Order = 3)]
    public string UserId { get; set; }
}

No comments: