Dealing with JSON serialization and camel casing in ASP.NET Core

ASP.NET Core Web APIs and controllers often need to serialize JSON data to JavaScript clients. On the server side your C# classes typically use Pascal Casing to name properties whereas JavaScript code often uses Camel Casing for property names. Therefore it would be worthwhile to take a quick look at how ASP.NET Core serializes data in JSON format from Web API and MVC controllers.

There are three common places from where C# objects are serialized in JSON format to the client:

  • Web API controllers
  • MVC controllers
  • Custom C# code using JsonSerializer

Camel casing and Web APIs

Let's first see the behavior of ASP.NET Core Web APIs when it comes to JSON serialization.

Consider the following Web API controller:

[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
 
    [HttpGet]
    public List<Employee> Get()
    {
        List<Employee> empList = 
new List<Employee>();
        empList.Add(new Employee() 
{ EmployeeID=1,FirstName="Nancy", 
LastName="Davolio" });
        empList.Add(new Employee() 
{ EmployeeID = 2, FirstName = "Andrew", 
LastName = "Fuller" });
        return empList;

    }
}

This code simply returns a List of Employee objects to the caller. The Employee class used in this code looks like this:

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

If you run the Get() action from the browser the Web API returns JSON data as shown below:

Notice this output carefully. You will find that the property names have automatically converted into their camel case equivalent. For example, EmployeeID became employeeID and FirstName became firstName. This means by default Web API serializes JSON data using camel casing.

What if you don't want this automatic conversion? What if you want to maintain whatever casing is being used by your C# classes?

Let's configure that behavior now.

Open the Startup class and modify the ConfigureServices() method as shown below:

public void ConfigureServices
(IServiceCollection services)
{
    services.AddControllers()
            .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions
.PropertyNamingPolicy = null;
                });
}

As you can see, the code uses the AddJsonOptions() method to configure this behavior. The PropertyNamingPolicy property of JsonSerializerOptions is set to null. After changing this setting if you run the Web API again, you will get the following output.

Notice that this time property name casing is preserved as it is in the C# class.

If you want to explicitly set the casing to camel casing then you can write :

options.JsonSerializerOptions.
ropertyNamingPolicy = JsonNamingPolicy.CamelCase;

Camel casing and MVC controllers

In ASP.NET Core MVC you can use Json() method to serialize data JSON format. Consider the following action that shows how this can be done.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        List<Employee> empList = 
new List<Employee>();
        empList.Add(new Employee() 
{ EmployeeID = 1, FirstName = "Nancy",
 LastName = "Davolio" });
        empList.Add(new Employee() 
{ EmployeeID = 2, FirstName = "Andrew", 
LastName = "Fuller" });
        return Json(empList);
    }
}

The Index() action creates a List of Employee objects. The empList is then serialized to the client using Json() method.

If you run this code with default configuration you will get the following output:

As you can see the property names use camel casing. This behavior is similar to the Web API behavior.

In order to instruct MVC to stop using camel casing you can write this code in the ConfigureServices().

services.AddControllersWithViews()
        .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions
.PropertyNamingPolicy = null;
            });

You used the AddJsonOptions() method on AddControllersWithViews().

And here is the output:

 

You can set PropertyNamingPolicy property to JsonNamingPolicy.CamelCase to explicitly set the property casing to camel casing.

You can also change this behavior for individual Json() calls as shown below:

var options = new JsonSerializerOptions()
{
    PropertyNamingPolicy = 
JsonNamingPolicy.CamelCase
};
return Json(empList, options);

Here, the code creates an object of JsonSerializerOptions class. It then sets PropertyNamingPolicy property to JsonNamingPolicy.CamelCase. Finally, the options object is passed as the second parameter of Json() method. This setting will take precedence over the setting specified in the ConfigureServices().

Custom code using JsonSerializer

At times you need to serialize data yourself via custom code. Typically you will use JsonSerializer to accomplish this task. Consider the following code:

public IActionResult Index()
{
    List<Employee> empList = 
new List<Employee>();
    empList.Add(new Employee() 
{ EmployeeID = 1, FirstName = "Nancy", 
LastName = "Davolio" });
    empList.Add(new Employee() 
{ EmployeeID = 2, FirstName = "Andrew", 
LastName = "Fuller" });

    string json = JsonSerializer.Serialize(empList);
    return Ok(json);
}

Here you used JsonSerializer class to serialize empList to JSON string. The string is then returned to the client by wrapping it in the Ok() method.

The output of this action in the browser looks like this:

As you can see, the Serialize() method of JsonSerializer doesn't use camel casing by default.

If you want JsonSerializer class to use camel casing you can do the following:

var options = new JsonSerializerOptions()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

string json = JsonSerializer.Serialize(empList, options);

return Ok(json);

As you can see, the code creates JsonSerializerOptions object and sets PropertyNamingPolicy property to JsonNamingPolicy.CamelCase. Then the Serialize() method is called by passing empList and JsonSerializerOptions object.

After this change the output will be:

As you can see, the JSON output now uses camel casing.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Kriya and Meditation online course are available here.

Posted On : 10 January 2022


Tags : ASP.NET ASP.NET Core Web Services Data Access MVC C# Visual Studio