Danny Tuppeny
Danny Tuppeny

Reputation: 42333

How do I control property names (casing) of JSON-deserialised objects through service/WebInvoke methods

I'm hosting a service using code like this:

// Set up the test service
testServiceHost = new WebServiceHost(typeof(TestTrelloService), testServiceAddress);
testServiceHost.Open();

And I'm sending a PUT with RestSharp, to a method like this:

[OperationContract]
[WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "cards/{cardId}?key={key}")]
public void UpdateCard(string key, string cardId, Card updatedCard)
{
    // ...
}

key and cardId are coming from the url/querystring, and updatedCard is the request body (s JSON).

Everything works fine if my Card class looks like this:

public class Card
{
    public string id { get; set; }
    // ...
}

The JSON data passed in the body is correctly deserialised into a Card object with the id propert set.

However, I want my class to have different casing on the property. It actually looks like this:

public class Card
{
    public string Id { get; set; }
}

However, this doesn't work. I've tried adding various attributes to try and control this (including [DataMember(Name="id")]), but nothing seems to work.

Is there a way I can control the property names for the JSON deserialisation done for my WebInvoke/service method?

Upvotes: 4

Views: 1299

Answers (1)

Danny Tuppeny
Danny Tuppeny

Reputation: 42333

Well, now I feel lame... I fixed it!

[DataContract]
public class Card
{
    [DataMember(Name = "id")]
    public string Id { get; set; }
}

I was missing the DataContract attribute, which appears to be required for it to read the DataMember attribute!

Upvotes: 2

Related Questions