.NET 8 – JSON serialize property names using snake case and kebab case
.NET 8 introduces several new naming policies that can be used with the System.Text.Json
serializer. To name them:
- SnakeCaseLower
- SnakeCaseUpper
- KebabCaseLower
- KebabCaseUpper
Let’s look at the serialized output for each of them. For this, we’re going to use a Car
class with the following definition:
class Car
{
public string Make { get; set; }
public string ModelID { get; set; }
public int LaunchYear { get; set; }
}
Code language: C# (cs)
And we are going to serialize the following object instance:
var car = new Car
{
Make = "Mazda",
ModelID = "MX-5",
LaunchYear = 1989
};
Code language: C# (cs)
Lower snake case (snake_case)
To serialize using lower snake_case, you need to specify JsonNamingPolicy.SnakeCaseLower
as the PropertyNamingPolicy
inside the serializer’s JsonSerializerOptions
. Like so:
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
JsonSerializer.Serialize(car, options);
Code language: C# (cs)
And the output will be:
{"make":"Mazda","model_id":"MX-5","launch_year":1989}
Code language: JSON / JSON with Comments (json)
Upper snake case (SNAKE_CASE)
Just like above, using JsonNamingPolicy.SnakeCaseUpper
as the property naming policy. The output will be:
{"MAKE":"Mazda","MODEL_ID":"MX-5","LAUNCH_YEAR":1989}
Code language: JSON / JSON with Comments (json)
Lower kebab case (kebab-case)
To serialize using lower kebab-case, you need to specify JsonNamingPolicy.KebabCaseLower
as the PropertyNamingPolicy
inside the serializer’s JsonSerializerOptions
. Like so:
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.KebabCaseLower };
JsonSerializer.Serialize(car, options);
Code language: C# (cs)
This will output the following JSON:
{"make":"Mazda","model-id":"MX-5","launch-year":1989}
Code language: JSON / JSON with Comments (json)
Upper kebab case (KEBAB-CASE)
Just like the previous example, but using JsonNamingPolicy.KebabCaseUpper
for the property naming policy. You will get the following output:
{"MAKE":"Mazda","MODEL-ID":"MX-5","LAUNCH-YEAR":1989}
Code language: JSON / JSON with Comments (json)
One Comment