Reputation: 14907
I have a Web API service that (to my surprise) needs to be able to accept XML as well as JSON. First, here are the models:
[DataContract]
public class SerializedCustomerEvent
{
[DataMember]
public string TypeID { get; set; }
[DataMember]
public ContextPair[] Context { get; set; }
}
public class ContextPair
{
public string Key { get; set; }
public string Value { get; set; }
}
Here is the API controller method:
public void Post(SerializedCustomerEvent value)
{
_queueBroker.Queue(value);
}
Now here's the part where I'm overlooking something. A JSON post from Fiddler works fine:
Content-Type: application/json; charset=utf-8
{
"TypeID":"ABC",
"Context":
[
{"Key":"Field1","Value":"123"},
{"Key":"Field2","Value":"Jeff"}
]
}
The XML version, however, doesn't work. The Context property is always null.
Content-Type: application/xml; charset=utf-8
<?xml version="1.0"?>
<SerializedCustomerEvent xmlns="http://schemas.datacontract.org/2004/07/MyNamespace">
<TypeID>XMLWow</TypeID>
<Context>
<ContextPair>
<Key>Field1</Key>
<Value>123</Value>
</ContextPair>
<ContextPair>
<Key>Field2</Key>
<Value>Jeff</Value>
</ContextPair>
</Context>
</SerializedCustomerEvent>
What am I missing here?
Upvotes: 0
Views: 343
Reputation: 3237
See this SO post: it's because the Data Contract expects the members to be in alphabetical order. So if you swap the TypeID and Context elements around in your source they'll both be populated in your object.
Upvotes: 2