Learner
Learner

Reputation: 1315

REST service how to pass JSON for parameters

I have created a WCF REST API:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,  
           BodyStyle = WebMessageBodyStyle.WrappedRequest,
           ResponseFormat = WebMessageFormat.Json, UriTemplate = "/checkEmail")]
RestResponse<bool> checkEmail(string EmailId);

JSON request is:

{ "EmailId" :"[email protected]" }

It is working as expected. But after some code review changes I changed the param in method to

checkEmail(string emailId);

i.e. changed it in to camel case. How can I modify my code to use same JSON request i.e. API call should remain same

{ "EmailId" :"[email protected]" }

Upvotes: 1

Views: 1141

Answers (1)

Frank Fajardo
Frank Fajardo

Reputation: 7359

This might work for you. It works in a limited test I did. I created a class which has two properties:

[DataContract]
public class EmailParms
{
    [DataMember]
    [JsonProperty(DefaultValueHandling=DefaultValueHandling.IgnoreAndPopulate)]
    public virtual string EmailId { get; set; }
    [DataMember]
    [JsonProperty(DefaultValueHandling=DefaultValueHandling.IgnoreAndPopulate)]
    public virtual string emailId { get; set; }
}

The JsonPropertyAttribute is part of Json.NET.

And then you change your checkEmail to have:

RestResponse<bool> checkEmail(Emailparms emailParms);

The IgnoreAndPopulate basically deserializes a property that is missing from that json data, and gives it the property's default value.

Now, in your method, you just have to check the values of emailId and EmailId in emailParms and decide which to use.

In my test, it worked for any of these:

{ "EmailId" :"[email protected]" }
{ "emailId" :"[email protected]" }
{ "EmailId" :"[email protected]", "emailId" :"[email protected]" }

Upvotes: 1

Related Questions