Bob
Bob

Reputation: 3084

Web Api 2 Json Formatter

Using Web Api 2, I have my JSON formatting setup correctly as far as I know and when returning a simple model, the data is formatted in camel case.

HttpConfiguration globalConfig = GlobalConfiguration.Configuration;
globalConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
globalConfig.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

For example a Model with property UserName is returned as userName to the client. The issue is that when I return an IEnumerable, the properties are not in camel case.

In all cases I return a IHttpActionResult with return this.Ok(result);

Upvotes: 1

Views: 327

Answers (1)

Ajay B L
Ajay B L

Reputation: 1106

As mentioned in this post, Whenever using IEnumerable with json response,

// camelcase properties when it is json response
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.OfType<JsonMediaTypeFormatter>().First();
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Refer to the link for more details :)

Upvotes: 1

Related Questions