2

I currently have my web API set up to return all JSON in a camelCase format with the following code in WebApiConfig:

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new 
Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

And it works wonderfully. However, I am using the jQuery Datatable plugin and am saving/loading the state through my API, and it requires the data to be returned in a TitleCase format. Now obviously I'm not going to rewrite my entire consuming application(s) to except TitleCase formated Json, so I need my LoadState route only to return TitleCase format.

I've tried things such as:

[HttpGet]
[Route("api/Controller/LoadState")]
public IHttpActionResult LoadState()
{
    var state = _eService.LoadState(UserProfile.IndividualId);

    //requires title cased object
    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings.ContractResolver = new DefaultContractResolver();

    return Ok(state);
}

But this seems to set the entire application to TitleCase and overwrite my settings in the WebApiConfig. Anyone have any recommendations?

Halter
  • 48
  • 2
  • 6
  • 30
  • See if this helps you: https://stackoverflow.com/questions/19956838/force-camelcase-on-asp-net-webapi-per-controller – Jason Boyd Aug 11 '17 at 16:39

2 Answers2

3

Use

var serializerSettings = new JsonSerializerSettings()
{ 
    ContractResolver = new DefaultContractResolver() 
};
// set any other settings here


return Json(state, serializerSettings);

The Json return method is what you want. It lets you specify custom serialization settings for that call.

MSDN Documentation for ApiController.Json

0

I faced a similar situation, I achieved this by doing some thing like this:

HttpResponseMessage response = Request.CreateResponse(System.Net.HttpStatusCode.OK, JsonConvert.SerializeObject(test, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }));

Hope this helps.

Debasish
  • 1
  • 1