JsonSerializerOptions
Learn indentation and naming policy with JsonSerializerOptions.
Format with JsonSerializerOptions
The JsonSerializerOptions class customizes serialization behavior. Two common settings: WriteIndented = true produces indented readable output; PropertyNamingPolicy = JsonNamingPolicy.CamelCase turns all keys to camelCase.
Usage: var options = new JsonSerializerOptions { WriteIndented = true }; and JsonSerializer.Serialize(p, options);. Configuring options once and passing them to each call ensures consistent formatting.
CamelCase naming policy
JsonNamingPolicy.CamelCase turns all key names into camelCase: first letter lowercase, subsequent word starts uppercase. PersonName becomes personName, Age becomes age.
This format is common in web APIs. Usage: var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };. With this, all properties without a [JsonPropertyName] attribute are adapted to camelCase.
Exercise Serialize with CamelCase
Create options with var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };. Then serialize the Person instance with JsonSerializer.Serialize(p, options) and print. Expected output: camelCase keys.
Show example solution
Create options with var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };, serialize with string text = JsonSerializer.Serialize(p, options);, print with Console.WriteLine(text);.
Example solution:
using System;
using System.Text.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var p = new Person { Name = "Alex", Age = 30 };
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
string text = JsonSerializer.Serialize(p, options);
Console.WriteLine(text);
}
}
Test yourself
-
What does WriteIndented = true do?
- Lowercases the keys
- Makes the output indented and readable
- Hides properties
- Writes to a file
Show answer
Makes the output indented and readable — Correct. WriteIndented = true makes the output indented and readable; it adds line breaks and spaces.
-
Match each setting to its output
- WriteIndented = true
- Indented output
- CamelCase
- camelCase keys
- (default)
- Compact output
- JsonPropertyName
- Custom key
-
Create options
var options = new ____ { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };Show answer
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };