0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ugh, that's embarrassing. What a strange requirement. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.