Web API 2: How to Return JSON with Camelcased Property Names, on Objects and Their Sub-Objects

Web API 2: how to return JSON with camelCased property names, on objects and their sub-objects

Putting it all together you get...

protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}

How do I configure WebApi to seralise objects without changing the casing of their property names

An answer does not seem forthcoming, and my position on the best tactic has changed anyway, so I will answer my own question by describing how I dealt with the underlying problem of inconsistent serialisation behaviour.

In fact the business of forcing a casing pattern is all about consistency and predictability. It doesn't really matter what the behaviour is, as long as it's predictable.

Forcing improves predictability: it's one or the other, and you can change all the results from a web api with a single setting. So forcing is better, and the question changes from "How can I prevent forcing?" to "How can I cause dynamics to be forced like all other types?"

The answer to that lies here: .NET Core json serialization of properties on dynamic (ExpandoObject)

That answer is for Core 1, here's how to do the same with Core 2

// in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
. . .
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
. . .
}

Configuring WebApi 2.0 such that controller.Json(...) returns camelCaseFormatted data

Try setting the JsonProperty attribute on model property as follows:


[JsonProperty("success")]
public bool Success { get; set; }

Automatically bind pascal case c# model from snake case JSON in WebApi

No need to reinvent the wheel. Json.Net already has a SnakeCaseNamingStrategy class to do exactly what you want. You just need to set it as the NamingStrategy on the DefaultContractResolver via settings.

Add this line to the Register method in your WebApiConfig class:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };

Here is a demo (console app) to prove the concept: https://dotnetfiddle.net/v5siz7


If you want to apply the snake casing to some classes but not others, you can do this by applying a [JsonObject] attribute specifying the naming strategy like so:

[JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class InputObjectDTO
{
public string FullName { get; set; }
public decimal TotalPrice { get; set; }
}

The naming strategy set via attribute takes precedence over the naming strategy set via the resolver, so you can set your default strategy in the resolver and then use attributes to override it where needed. (There are three naming strategies included with Json.Net: SnakeCaseNamingStrategy, CamelCaseNamingStrategy and DefaultNamingStrategy.)


Now, if you want to deserialize using one naming strategy and serialize using a different strategy for the same class(es), then neither of the above solutions will work for you, because the naming strategies will be applied in both directions in Web API. So in in that case, you will need something custom like what is shown in @icepickle's answer to control when each is applied.

Serialize JSON property name with comma in its name?

You can use JsonPropertyName attribute to map the json to the property e.g:

[JsonPropertyName("@odata.context")] 
public string DataContext { get ; set; }

Microsoft docs



Related Topics



Leave a reply



Submit