受欢迎的博客标签

Dealing With Camel Casing In ASP.NET Core Web API

Published

Web defaults for System.Text.Json JsonSerializerOptions 

There's a JsonSerializerOptions constructor that lets you create a new instance with the different options.

Here are the options that have different defaults for web apps:

PropertyNameCaseInsensitive = true
JsonNamingPolicy = CamelCase
NumberHandling = AllowReadingFromString

Official Documentation:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-configure-options?pivots=dotnet-5-0

 

4.1 ASP.NET Core 6.x-use System.Text.Json

 

program.cs  in BlazorServer

var builder = WebApplication.CreateBuilder(args);

//come from:https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-6.0

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // Use the default property (Pascal) casing.
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
        // Configure a custom converter.
        options.JsonSerializerOptions.Converters.Insert(0, new JsonObjectIdConverterUsingSystemTextJson());
    });

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

 

 

3.1ASP.NET Core 5.x-use System.Text.Json

startup.cs

using System.Text.Json;  //for   options.JsonSerializerOptions.PropertyNamingPolicy

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            //services.AddControllers();

            //不转换大小写
            services.AddControllers()
                     .AddJsonOptions(options =>
                     {
                          // Use the default property (Pascal) casing.
                         options.JsonSerializerOptions.PropertyNamingPolicy = null;
                     }
                );


        }

vist:

https://testapi.stockso.com/api/v1/StockDataPhysicalDiskMultiFilterPankou/MenuAsync

{"bs":null,"DayNum":1,"IsStopTrading":false,"IsSingleStock":true,"PriceRangeList":[{"IsEnabled":false,"Selected":false,"From":0,"To":999},{"IsEnabled":false,"Selected":false,"From":1000,"To":1999},{"IsEnabled":false,"Selected":false,"From":2000,"To":2999},{"IsEnabled":false,"Selected":true,"From":3000,"To":5000}]}

 

before

[{"name":"QJ12B-Y","id":"5f43a46054a35fe1d20785d0"},{"name":"FS1","id":"5f43a46054a35fe1d2078633"}]

 Now

[{"Name":"QJ12B-Y","id":"5f43a46054a35fe1d20785d0"},{"Name":"FS1","id":"5f43a46054a35fe1d2078633"}]

 

3.2ASP.NET Core 5.x-use Newtonsoft.JSON


Adding Newtonsoft JSON serialization and deserialization in ASP.NET Core 5.x

if you would like to continue to use JSON.NET as default serializer, kindly follow the below steps.

Add a reference to NewtonsoftJson Nuget package

PM> Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson Version=5.0.2

You can still set it application wide by installing Microsoft.AspNetCore.Mvc.NewtonsoftJson Nuget Package, which allows you to use the previous Json serializer implementation.In order to reconfigure your ASP.NET Core 5.x project with Json.NET, you will need to add a NuGet reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson, which is the package that includes all the necessary bits. Then, in the Startup’s ConfigureServices, you will need to configure MVC like this:

 services.AddControllers()
             .AddNewtonsoftJson();

or

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
         // Use the default property (Pascal) casing
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

 

1.ASP.NET Core 3.x-use System.Text.Json

ASP.NET Core 3.x uses it’s own JSON serializer i.e ‘System.Text.Json‘ which is lightweight and very efficient.

The release of .NET Core 3  includes a brand new serializer for JavaScript Object Notation (JSON) under the System.Text.Json namespace. The Microsoft documentation states,

1.1 System.Text.Json

ASP.NET Core 3.x System.Text.Json Camel Case Serialization

As part of ASP.NET Core 3.0, the team moved away from including Json.NET by default.

1.1.1 AddJsonOptions() would config System.Text.Json only for MVC.

In startup.cs

// keeps the casing to that of the model when serializing to json (default is converting to camelCase)
services.AddMvc()
    .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null); 

1.1.2 Serializing an Object to JSON

If you want to use JsonSerializer in your own code you should pass the config to it.

You can use PropertyNameCaseInsensitive. You need to pass it as a parameter to the deserializer.

ar json = "{\"firstname\":\"John\",\"lastname\":\"Smith\"}";
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
var person = JsonSerializer.Deserialize<Person>(json, options);

Official Documentation:

https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.propertynamecaseinsensitive?view=netcore-3.0

1.1.3 Making application level changes for JSON serialization

Globally Configuring Values For JSON Serializer In ASP.NET Core 3.1
If you want PascalCase serialization use this code in Startup.cs:
services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy= null;
        );
If you want camelCase serialization use this code in Startup.cs:
services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        });

2.ASP.NET Core 3.x-use Newtonsoft.JSON

Adding Newtonsoft JSON serialization and deserialization in ASP.NET Core 3.1

ASP.NET Core 3.0  has removed the dependency on JSON.NET. So there is no default Newtonsoft based serialization and deserialization.

But however, if you would like to continue to use JSON.NET as default serializer, kindly follow the below steps.

Add a reference to NewtonsoftJson Nuget package

PM> Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.2

You can still set it application wide by installing Microsoft.AspNetCore.Mvc.NewtonsoftJson Nuget Package, which allows you to use the previous Json serializer implementation.In order to reconfigure your ASP.NET Core 3.0 project with Json.NET, you will need to add a NuGet reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson, which is the package that includes all the necessary bits. Then, in the Startup’s ConfigureServices, you will need to configure MVC like this:

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

 

ASP.NET Core 2.x-use Newtonsoft.Json

If you worked with that example you must have noticed that while serializing data to the client, the ASP.NET Core Web API uses camel casing. That means if your server side C# class is like this :

[Table("Employees")]
public class Employee
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int EmployeeID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string City { get; set; }
}

then post JSON serialization a sample Employee object will look like this :

{
 "employeeID":1,
 "firstName":"Nancy",
 "lastName":"Davolio",
 "city":"Seattle"
}

Firefox nicely shows the output as shown in the following figure.

 

As you can see all the property names have been converted to their camel case equivalents (EmployeeID to employeeID, FirstName to firstName and so on).

This default behavior doesn't post much problems if the client is a C# application (HttpClient based) but if the client is a JavaScript client you might need to alter this behavior. Even with JavaScript clients the camel casing may not pose any problem in many cases. That's because camel casing is heavily used in JavaScript world. Especially if you are using some JS framework chances are you will be using camel casing during data binding and similar things.

At times, however, you may want to preserve the casing of the original C# property names. Suppose you are migrating or reusing an existing piece of JavaScript code that uses the same casing as the C# class. So, you might want to prevent that code from breaking. This requires that the JSON serialization of ASP.NET Core preserve the casing of the underlying C# class.

Although the default behavior is to use camel casing, you can easily change that to preserve the original casing. Let's see how.

Open the Startup class of the Web API application and go to the ConfigureServices() method. Currently you have the following call there:

services.AddMvc();

Change that line to this:

services.AddMvc()
        .AddJsonOptions(options => 
        options.SerializerSettings.ContractResolver
         = new DefaultContractResolver());

The above code uses AddJsonOptions() extension method. The AddJsonOptions() method then specifies the ContractResolver property to an instance of DefaultContractResolver class. Note that for the above code to compile correctly you need to do the following:

  • Import Newtonsoft.Json.Serialization namespace
  • Add NuGet package for Microsoft.AspNetCore.Mvc.Formatters.Json (see below)

 

 

If you run the application now, you should see the JSON data as shown below.

 

As you can see, now the camel casing has been removed. Remember that DefaultContractResolver preserves whatever is the casing of the C# class. It doesn't automatically convert it to pascal casing. Just to make this clear have a look at the following figure.

 

Observe the casing of the properties. The underlying C# class has been modified to use the casing as shown above. The same casing is preserved during JSON serialization.

What if you need to explicitly specify that you want camel casing? Simple. Just use CamelCasePropertyNamesContractResolver class. The following code shows how.

services.AddMvc()
        .AddJsonOptions(options => 
        options.SerializerSettings.ContractResolver 
        = new CamelCasePropertyNamesContractResolver());

Now we set the ContractResolver to a new instance of CamelCasePropertyNamesContractResolver class. This will use camel casing during JSON serialization.

That's it for now! Keep coding!!

驼峰

 

Resource:. 

Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?

ASP.NET Core 3.0 System.Text.Json Camel Case Serialization