Web API serializes properties starting with a lowercase letter

How do I serialize my web API to use camelCase property camelCase (starting with a lowercase letter) instead of PascalCase , as shown in C #.

Can I do this globally for the entire project?

+46
c # asp.net-mvc asp.net-web-api
Mar 02 '14 at 16:48
source share
4 answers

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

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

You can also pass these settings to JsonConvert.SerializeObject :

 JsonConvert.SerializeObject(objectToSerialize, serializerSettings); 

For ASP.NET MVC and web API. At 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 the resulting JSON.

ASP.NET Kernel

The ASP.NET core serializes values ​​in camelCase format by default.

+79
Mar 02 '14 at 16:54
source share

For MVC 6.0.0-rc1-final

Change Startup.cs, In ConfigureServices(IserviceCollection) change services.AddMvc();

 services.AddMvc(options => { var formatter = new JsonOutputFormatter { SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()} }; options.OutputFormatters.Insert(0, formatter); }); 
+6
03 Feb '16 at 23:07
source share

ASP.NET CORE 1.0.0 The Json series have a standard camelCase by default. Judge of this announcement

+2
Jul 08 '16 at 6:40
source share

If you want to do this in the new (vNext) C # 6.0, you need to configure it using MvcOptions in the ConfigureServices method located in the Startup.cs class Startup.cs .

 services.AddMvc().Configure<MvcOptions>(options => { var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); jsonOutputFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore; options.OutputFormatters.Insert(0, jsonOutputFormatter); }); 
+1
May 24 '15 at 21:44
source share



All Articles