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

时间:2014-03-02 16:48:58

标签: c# .net asp.net-mvc asp.net-web-api json.net

如何配置Web API的序列化以使用camelCase(从小写字母开始)属性名称而不是{C}中的PascalCase

我可以为整个项目全球化吗?

4 个答案:

答案 0 :(得分:85)

如果要更改Newtonsoft.Json(即JSON.NET)中的序列化行为,则需要创建设置:

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 Core

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

答案 1 :(得分:6)

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

答案 2 :(得分:2)

ASP.NET CORE 1.0.0 Json序列化具有默认的camelCase。 Referee this Announcement

答案 3 :(得分:1)

If you want to do this in the newer (vNext) C# 6.0, then you have to configure this through MvcOptions in the ConfigureServices method located in the Startup.cs class file.

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