แบบฝึกหัด C#

JSON Round Trip

A round trip is a practical way to verify a model's JSON representation.

How it works

Serialize and deserialize a typed record.

System.Text.Json uses public constructor parameters and properties to reconstruct the record.

Runnable C# example

C#
Run code →
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}");
    }
}
Expected output
dark: 16

Practice 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.