C# & .NET

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

This post was most recently updated on February 22nd, 2022.

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 definitely run into this again.

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

Problem

Imagine that 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 perhaps you’re doing something like this, to maybe return JSON from your ASP.NET Controller as a response 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.

So, instead of this:

{
  "type": "This one is in camelCase"
}

You’ll get something like this:

{
  "Type": "This one is in PascalCase"
}

Depending on what you’re actually trying to do, you might or might not mind this. This might be fine.

But I certainly did. Or rather, my front-end developer colleague did. He wanted all methods to return JSON in camelCase.

So I needed to fix it :)

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.Serialize() 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:


Alternatively, you can achieve the same with Newtonsoft, but since its functionality gets absorbed into .NET (and isn’t exactly compatible in later versions), I’m doing this in pure .NET using System.Text.Json.

The code sample should work at least for .NET Core 3.1 and .NET 5.


Did it work for you? Not what you were looking for? Let me know in the comments-section below!

References

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