Web API序列化从小写字母开始的属性

如何configuration我的Web API的序列化来使用camelCase (从小写字母开始)属性名称而不是像C#中的PascalCase

我可以在整个项目中进行全球化吗?

如果你想改变Newtonsoft.Json又名JSON.NET的序列化行为,你需要创build你的设置:

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

您也可以将这些设置传递给JsonConvert.SerializeObject

 JsonConvert.SerializeObject(objectToSerialize, serializerSettings); 

对于ASP.NET MVC和Web API。 在Global.asax中:

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

排除空值:

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

指示在结果JSON中不应该包含空值。

ASP.NET核心

ASP.NET Core默认以camelCase格式序列化值。

对于MVC 6.0.0-rc1-final

编辑Startup.cs ,在ConfigureServices(IserviceCollection) ,修改services.AddMvc();

 services.AddMvc(options => { var formatter = new JsonOutputFormatter { SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()} }; options.OutputFormatters.Insert(0, formatter); }); 

ASP.NET CORE 1.0.0 Json序列化具有默认的camelCase。 裁判本公告

如果要在较新的(vNext)C#6.0中执行此操作,则必须通过位于Startup.cs类文件中的ConfigureServices方法中的MvcOptions进行ConfigureServices

 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); });