WCF and posting JSON to REST API

Recently I had to post a JSON to my REST API and for some reason my data was being deserialized as null.

The reason was the JSON element’s name was in CamelCase, while the API parameter name was in pascalCase. While investigating this issue I came upon another interesting tidbit, so I wanted to share. As you know, API interface can be marked with an attribute [WebInvoke] which can be constructed using a parameter BodyStyle. The values for the parameter I’ve played around are:

  • No parameter supplied:
    • You must post the request without any element around the JSON structure:
[{
  "UserLevel": 2,
  "Users": []
  ,
  "Description": "someText"
  }, 
{
  "ConsentLevel": 2,
  "Users": []
  ,
  "Description": "someText"
}]
  • BodyStyle=WebMessageBodyStyle.Wrapped:
    • You must post the request with an element surrounding the JSON structure. Pay attention to the leading element consentGroups. This is the approach I decided upon, as it provides more flexibility (your API method can have multiple parameters this way):
      {
        "consentGroups":[{
             "UserLevel": 2,
             "Users": []
             ,
             "Description": "someText"
            }, {
             "UserLevel": 2,
             "Users": []
             ,
             "Description": "someText"
           }]
      }

Leave a comment