.NET 11 Preview - Pascal Case Json Serialization
[C#, .NET, .NET 11 Preview, System.Text.Json]
When serializing JSON, you have some leeway to specify exactly how you want the property names to be serialized. This is useful in cases where you do not control the consumer of your output, that might be fussy about the property naming.
Alternatively, you might want to adapt to the convention of the ecosystem you are integrating with. For example Python generally uses snake case.
We can control this using the JsonSerializationOptions class, as outlined below.
First we have our type:
public sealed class Person
{
public required string FirstName { get; set; }
public required string Surname { get; set; }
}
And then the code that serializes our type:
// Camel case
Console.WriteLine("Camel Case");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }));
// Kebab case, lower
Console.WriteLine("Kebab Case, Lower");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.KebabCaseLower, WriteIndented = true }));
// Kebab case, upper
Console.WriteLine("Kebab Case, Uppter");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.KebabCaseUpper, WriteIndented = true }));
// Snake case, lower
Console.WriteLine("Snake Case, Lower");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, WriteIndented = true }));
// Snake case, upper
Console.WriteLine("Snake Case, Upper");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseUpper, WriteIndented = true }));
// Pascal Case
Console.WriteLine("Pascal Case");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.PascalCase, WriteIndented = true }));
This will output the following:
{
"firstName": "James",
"surname": "Bond"
}
{
"first-name": "James",
"surname": "Bond"
}
{
"FIRST-NAME": "James",
"SURNAME": "Bond"
}
{
"first_name": "James",
"surname": "Bond"
}
{
"FIRST_NAME": "James",
"SURNAME": "Bond"
}
Here we can see the following policies are supported:
In .NET 11, there is an additional one - PascalCase.
Console.WriteLine("Pascal Case");
Console.WriteLine(JsonSerializer.Serialize(person, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.PascalCase, WriteIndented = true }));
This will output the following:
{
"FirstName": "James",
"Surname": "Bond"
}
TLDR
You can now output JSON properties in PascalCase
The code is in my GitHub.
Happy hacking!