Data and Formats · Lesson 1

Serialize a small model

Turn public data properties into a JSON document.

How it works

Serialization converts the data exposed by an object into another representation. JsonSerializer serializes the public properties of this record into JSON. The resulting document describes the name and count, not the record’s methods or executable behavior. Property names use their declared casing unless an option or attribute changes the contract. Keep transport data simple and avoid serializing a large application object graph by accident.

A stable public format needs an explicit schema and compatibility rules: adding a property may be easy, while changing a property’s type can break existing readers even when the new object looks convenient internally.

Add a boolean property and inspect the document. Decide whether a consumer expecting the original fields can ignore the new field, and distinguish that from changing Count into text.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var item = new StockItem("rune", 3);
Console.WriteLine(JsonSerializer.Serialize(item));
record StockItem(string Name, int Count);

Expected output

{"Name":"rune","Count":3}
Try this
A serialized document is a data contract, not a copy of executable behavior.