JSON Round Trip
Serialize and deserialize a typed record.
Introduction
A round trip is a practical way to verify a model's JSON representation.
System.Text.Json uses public constructor parameters and properties to reconstruct the record.
Runnable C# example
Program.cs
using System;
using System.Text.Json;
record Settings(string Theme, int FontSize);
class Program
{
static void Main()
{
string json = JsonSerializer.Serialize(new Settings("dark", 16));
Settings? settings = JsonSerializer.Deserialize<Settings>(json);
Console.WriteLine($"{settings?.Theme}: {settings?.FontSize}");
}
}
dark: 16Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Build a JSON Object Turn keys and values into a JSON object string, escaping quotes and backslashes correctly. Easy
- Sum a Flat JSON Object Parse a flat JSON object whose values are integers and add up the values. Easy