.net Web API serialize properties starting from lowercase letter

o75abkj4  于 2022-12-14  发布在  .NET
关注(0)|答案(5)|浏览(81)

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?

jucafojl

jucafojl1#

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.

mwkjh3gx

mwkjh3gx2#

For MVC 6.0.0-rc1-final
Edit Startup.cs, In the ConfigureServices(IserviceCollection) , modify services.AddMvc();

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

gr8qqesn3#

ASP.NET核心1.0.0 Json序列化具有默认camelCase.Referee this Announcement

xmjla07d

xmjla07d4#

如果您想在更新的(vNext)C# 6.0中执行此操作,则必须通过Startup.cs类文件中ConfigureServices方法中的MvcOptions进行配置。

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

tjvv9vkg5#

正如其他人所指出的,camelCase是默认的,但是如果你不想在任何地方都这样,你可以像这样注解你的类。

using System.Text.Json.Serialization;

public class Developer
{
    [JsonPropertyName("Id")]
    public int Id { get; set; }
    [JsonPropertyName("FirstName")]
    public string? FirstName { get; set; }
    [JsonPropertyName("LastName")]
    public string? LastName { get; set; }
    [JsonPropertyName("RowNum")]
    public int RowNum { get; set; }
    [JsonPropertyName("StartDate")]
    public DateTime StartDate { get; set; }

}

相关问题