JSON Serialization with System.Text.Json
Convert C# objects to JSON and back using System.Text.Json, configure naming and formatting, and serialize enum values as readable strings.
Part 1: What You Will Learn
Convert C# objects to JSON and back using System.Text.Json, configure naming and formatting, and serialize enum values as readable strings.
- Serialize an object with `JsonSerializer.Serialize()`.
- Deserialize JSON with `JsonSerializer.Deserialize<T>()`.
- Configure camelCase property names and indented output.
- Use `JsonStringEnumConverter` so enum values are stored as text instead of numbers.
Project setup: Create a .NET 10 Console App. `System.Text.Json` is part of .NET and requires no separate package.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
using System.Text.Json;
using System.Text.Json.Serialization;
public enum ProductStatus
{
InStock,
BackOrder,
Discontinued
}
public record Product(
int Id,
string Name,
decimal Price,
ProductStatus Status);
JsonSerializerOptions options = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
options.Converters.Add(new JsonStringEnumConverter());
Product product = new(
101,
"Mechanical Keyboard",
299.90m,
ProductStatus.InStock);
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json);
Product? restored =
JsonSerializer.Deserialize<Product>(json, options);
Console.WriteLine(
$"Restored: {restored?.Name} - {restored?.Status}");Part 3: How the Code Works
- The serializer uses the C# object graph to produce a JSON document.
- `JsonNamingPolicy.CamelCase` changes JSON names such as `ProductStatus` to camelCase conventions.
- `JsonStringEnumConverter` produces values such as `"inStock"` or `"InStock"` depending on configuration rather than numeric enum values.
- Use source-generated serialization metadata when startup time, trimming, or high-throughput serialization is important.
Part 4: Mini Project & Practice
Mini project: create a List<Product>, save it to products.json with `File.WriteAllTextAsync`, read the file back, and deserialize it into a list.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 23.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition