27
Lesson 27 of 35 ยท Data & Storage

JSON & Serialization

JSON (JavaScript Object Notation) is the universal data exchange format. .NET 10 ships System.Text.Json with excellent performance and native AOT support.

Serialising Objects to JSON

JsonSerializer.Serialize() converts any object to a JSON string. Pass JsonSerializerOptions for pretty-printing or custom naming policies.

Serialize Serialize.cs
using System.Text.Json;

public record Product(string Name, decimal Price, int Stock);

var products = new List
{
    new("Widget", 9.99m,  100),
    new("Gadget", 29.99m, 50),
    new("Doohickey", 4.99m, 200)
};

var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(products, options);
Console.WriteLine(json);
await File.WriteAllTextAsync("products.json", json);

Deserialising JSON

JsonSerializer.Deserialize<T>() parses a JSON string back into .NET objects.

Deserialise Deserialize.cs
string json = await File.ReadAllTextAsync("products.json");
var products = JsonSerializer.Deserialize>(json);

foreach (var p in products ?? [])
    Console.WriteLine($"{p.Name}: {p.Price:C2} ({p.Stock} in stock)");

JsonPropertyName & Ignoring Fields

Use [JsonPropertyName] to map to a different JSON key. Use [JsonIgnore] to exclude properties from serialisation.

Attributes JsonAttribs.cs
using System.Text.Json.Serialization;

public class User
{
    [JsonPropertyName("full_name")]
    public string FullName { get; set; } = "";

    [JsonIgnore]
    public string Password { get; set; } = ""; // never serialised

    public string Email { get; set; } = "";
}