C# & .NET

How to serialize to JSON in camelCase using .NET Core?

This post was most recently updated on September 7th, 2021.

2 min read.

This article describes how to configure your .NET Core application to serialize objects in camelCase instead of PascalCase. I guess this is another quick note – something that should be simple, but I couldn’t remember how to do it from the top of my head, and the solution turned out to be a bit unintuitive. I guess that makes it worth documenting because I’ll run into this again for sure.

Anyway – let’s take a closer look at the actual issue at hand, shall we?

Problem

Imagine You’re doing something like this to push an object down a WebSocket as JSON:

string jsonString = JsonSerializer.Serialize(m);
byte[] buffer = Encoding.ASCII.GetBytes(jsonString);
socket.SendAsync(new ArraySegment(buffer), WebSocketMessageType.Text, true, CancellationToken.None);

Or just this, to maybe respond to an API call:

[HttpGet]
public async Task<IActionResult> Get ()
{
	var obj = await _srv.GetObject();
	string jsonString = JsonSerializer.Serialize(obj);

	return new OkObjectResult(jsonString);
}

If you’re then parsing this result into JavaScript, you’ll run into a small but annoying inconsistency: while in JavaScript, the naming convention is camelCase by default, .NET will happily serialize your objects as PascalCase, where the first letter will be uppercase.

Depending on what you’re actually trying to do, you might or might not mind this. I certainly did. Or rather, my front-end developer colleague did. So I needed to fix this :)

Reason

The default casing is PascalCase. Changing this requires a bit of configuration, and is not intuitive. But we’ll figure this out, no worries!

Solution

Let’s embark on a journey to fix this!

Time needed: 5 minutes.

How to configure your .NET web application to return JSON in camelCase?

  1. Configure Startup.cs

    First of all, add this dependency (if you don’t have it already):

    using System.Text.Json;

    Then add this in ConfigureServices():

    services
    .AddJsonOptions(options =>
    {
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });


    See what’s going on there? We’re setting the PropertyNamingPolicy to use camelCase by default.

  2. Change your call to JsonSerializer to include options

    In case just setting the default didn’t work – for me, it didn’t – you can also supply JsonSerializer with the optional JsonSerializerOptions object and override the casing there.

    Here’s how to do this:

    Change this:
    string jsonString = JsonSerializer.Serialize(m);

    To this:
    string jsonString = JsonSerializer.Serialize(m, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });

  3. Rebuild and run

    You’re done! Nice and easy :)

    Now you should get camelCase Property naming:
    This image has an empty alt attribute; its file name is image-1.png

Alternatively, you can achieve the same with Newtonsoft, but since it’s functionality getting absorbed into .NET (and isn’t exactly compatible in later versions), I’m doing this in pure .NET. The code sample should work at least for .NET Core 3.1 and .NET 5.

References

mm
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments