Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API serialize properties starting from lowercase letter

How can I configure serialization of my Web API to use camelCase (starting from lowercase letter) property names instead of PascalCase like it is in C#.

Can I do it globally for the whole project?

like image 498
Andrei Avatar asked Mar 02 '14 16:03

Andrei


People also ask

Should JSON properties be LowerCase?

property names must start with lower case letter. Dictionary must be serialized into jsonp where keys will be used for property names. LowerCase rule does not apply for dictionary keys.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

If you want to change serialization behavior in Newtonsoft.Json aka JSON.NET, you need to create your settings:

var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings  {      ContractResolver = new CamelCasePropertyNamesContractResolver(),     NullValueHandling = NullValueHandling.Ignore // ignore null values }); 

You can also pass these settings into JsonConvert.SerializeObject:

JsonConvert.SerializeObject(objectToSerialize, serializerSettings); 

For ASP.NET MVC and Web API. In Global.asax:

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

Exclude null values:

GlobalConfiguration.Configuration     .Formatters     .JsonFormatter     .SerializerSettings     .NullValueHandling = NullValueHandling.Ignore; 

Indicates that null values should not be included in resulting JSON.

ASP.NET Core

ASP.NET Core by default serializes values in camelCase format.

like image 166
Andrei Avatar answered Oct 09 '22 01:10

Andrei