JSON serialization contracts
JSON serialization contracts
Serialization converts an object into a representation suitable for storage or transport. Deserialization reads that representation into a chosen type. System.Text.Json supplies JSON support; successful parsing alone does not establish that business data is valid.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. File examples require an authorized disposable environment with a writable temporary directory and no concurrent writers.
Round-trip a typed object
A DTO (data transfer object) describes the fields exchanged with another component. The ordinary JsonSerializer defaults preserve public property names. Use matching options when writing and reading.
using System;using System.Text.Json;var item = new StockItem { Name = "Tea", Quantity = 4 };string json = JsonSerializer.Serialize(item);var restored = JsonSerializer.Deserialize<StockItem>(json)!;Console.WriteLine(restored.Name);Console.WriteLine(restored.Quantity);public sealed class StockItem{ public string Name { get; set; } = ""; public int Quantity { get; set; }}The known locally produced JSON restores the same two property values. The null-forgiving operator is justified only by this controlled non-null fixture.
Expected output (reasoned, not executed):
Tea4Choose a naming and compatibility policy
PropertyNamingPolicy controls JSON property naming in both directions. Default deserialization normally ignores unknown properties; UnmappedMemberHandling can instead reject them. Strictness is a contract decision, not a universal improvement.
using System;using System.Text.Json;using System.Text.Json.Serialization;var options = new JsonSerializerOptions{ PropertyNamingPolicy = JsonNamingPolicy.CamelCase, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow};string json = JsonSerializer.Serialize(new Product { ItemCount = 2 }, options);Console.WriteLine(json);try{ JsonSerializer.Deserialize<Product>("{\"itemCount\":2,\"extra\":1}", options);}catch (JsonException){ Console.WriteLine("Unexpected field");}public sealed class Product { public int ItemCount { get; set; } }The single known property becomes itemCount. The strict reader rejects extra rather than silently dropping it.
Expected output (reasoned, not executed):
{"itemCount":2}Unexpected fieldValidate presence and domain values
Required properties enforce presence, not a business rule such as a positive quantity. A JSON null can also yield a null object. Treat malformed JSON, absent required fields and invalid values as distinct conditions.
using System;using System.Text.Json;foreach (string json in new[] { "{}", "{\"Quantity\":-1}", "{\"Quantity\":3}", "null" }){ try { var item = JsonSerializer.Deserialize<Stock>(json); Console.WriteLine(item is not null && item.Quantity >= 0 ? "Valid" : "Invalid data"); } catch (JsonException) { Console.WriteLine("Invalid JSON contract"); }}public sealed class Stock { public required int Quantity { get; init; } }Missing Quantity fails required-member handling. A negative number is valid JSON and the correct CLR type, but invalid inventory data.
Expected output (reasoned, not executed):
Invalid JSON contractInvalid dataValidInvalid dataCommon mistakes and edge cases
For external data, enforce size and nesting limits before or during parsing, select known DTO types, and validate ranges and required business fields. Do not instantiate arbitrary polymorphic types. Custom converters translate special representations; source generation produces metadata or serialization code at build time and has different compatibility and AOT considerations. These are follow-up topics, not implemented in the examples. Avoid assuming console defaults equal ASP.NET Core web defaults. In .NET 10, RespectRequiredConstructorParameters and RespectNullableAnnotations are separate opt-in policies: presence and explicit null are distinct, and neither replaces domain validation. AllowDuplicateProperties = false rejects duplicate JSON property names; it is separate from rejecting unknown properties. For a DOM, dispose the JsonDocument and clone any JsonElement returned beyond that lifetime. These policies still need an input byte budget.
Practice and recap
Add a required string Code and a domain rule that it cannot be empty. Classify missing Code, empty Code, and a valid code with quantity zero.
Hint: Check required presence separately from string content and quantity.
Learning objective: Round-trip a typed synthetic record. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JSON serialization contracts — knowledge check
Apply the lesson concepts to the following scenarios.
What is a DTO?
What does CamelCase change for ItemCount?
What does Disallow do for an unknown JSON member?
Does required int Quantity reject negative integers?
Can Deserialize return null for a reference type?