The Analogy: The Standard Box
Before the shipping container, moving goods between a lorry, a ship and a train meant unpacking and repacking at every step, by hand, badly. The container fixed it with an agreed box: standard corners, standard size, standard lifting points. Nobody at the far port needs to know what is inside — only how to lift the box.
JSON is that box for objects. Your Order class lives in memory as references, properties and typed fields that only the CLR understands. A Python service, a browser, a message queue and a log aggregator understand none of it. Serialization flattens the object into an agreed text format that all of them can lift, and deserialization unpacks it back into a real Order at the other end.
The container analogy also carries the warning. A box is only interchangeable if both ends agree on the standard: the same names, the same casing, the same date format, the same idea of what null means. Nearly every JSON bug is a disagreement about the box, not about the goods — a price_usd that arrived as priceUsd, an enum sent as "Shipped" where a number was expected, a field silently dropped because nobody was watching.
Syntax or Core Structure
System.Text.Json is built into .NET. Two static methods do almost everything, and attributes handle the mismatches between your C# names and the wire format.
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
[JsonPropertyName("price_usd")] // the wire name wins
public decimal Price { get; set; }
[JsonIgnore] // never leaves the building
public string Internal { get; set; } = "secret";
public string[] Tags { get; set; } = Array.Empty<string>();
}
class Program
{
static void Main()
{
var product = new Product
{
Id = 7,
Name = "Desk Lamp",
Price = 24.5m,
Tags = new[] { "home", "lighting" }
};
// 1. Defaults: PascalCase kept, no whitespace.
Console.WriteLine(JsonSerializer.Serialize(product));
// 2. Same object, different box.
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
Console.WriteLine(JsonSerializer.Serialize(product, options));
// 3. Unpack a payload whose casing does not match the class.
string incoming = """{"id":9,"name":"Chair","price_usd":89.99,"tags":["office"]}""";
Product back = JsonSerializer.Deserialize<Product>(
incoming,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
Console.WriteLine(back.Name + " " + back.Price + " " + back.Tags.Length + " " + back.Internal);
}
}
Output:
{"Id":7,"Name":"Desk Lamp","price_usd":24.5,"Tags":["home","lighting"]}
{
"id": 7,
"name": "Desk Lamp",
"price_usd": 24.5,
"tags": [
"home",
"lighting"
]
}
Chair 89.99 1 secret
Three things in that output are worth pinning down. Properties come out in declaration order, which is why Id leads. [JsonPropertyName] beats the naming policy, so price_usd survives camelCasing untouched. And Internal never appears on the wire yet still reads secret after the round trip, because [JsonIgnore] removed it from the box, not from the object — the property simply kept its initialiser.
Technical Depth: What the Box Standard Actually Says
The defaults, and why they surprise people
System.Text.Json was written to be fast and strict, not forgiving. Its defaults are deliberately narrow:
| Behaviour | Default | Change it with |
|---|---|---|
| Property name matching | Case-sensitive | PropertyNameCaseInsensitive = true |
| Output names | Exactly as declared | PropertyNamingPolicy = JsonNamingPolicy.CamelCase |
| Fields (not properties) | Ignored | IncludeFields = true or [JsonInclude] |
| Enums | Written as numbers | new JsonStringEnumConverter() |
null properties | Written as null | DefaultIgnoreCondition |
| Comments and trailing commas | Throw | ReadCommentHandling, AllowTrailingCommas |
| Numbers quoted as strings | Throw | NumberHandling = AllowReadingFromString |
| Object cycles | Throw | ReferenceHandler.IgnoreCycles |
JsonSerializerDefaults.Web flips the three that matter most for HTTP work in one go: camelCase output, case-insensitive reading, and numbers readable from strings. It is what ASP.NET Core uses, so an API client built with new JsonSerializerOptions(JsonSerializerDefaults.Web) speaks the same dialect as the server.
Reuse the options object
This is the single most common performance mistake with System.Text.Json:
// SLOW: every call builds a fresh metadata cache for every type it touches.
JsonSerializer.Serialize(order, new JsonSerializerOptions { WriteIndented = true });
// FAST: one instance, reused forever.
static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
JsonSerializer.Serialize(order, Json);
An options instance caches the reflection work it did for each type. Construct a new one per call and you pay for that reflection every time — often a 10x-plus difference in a hot loop. Options become read-only on first use, so a static readonly field is both the fast and the safe shape.
Immutable types and constructors
Records and other read-only types deserialize fine. If exactly one public constructor exists, System.Text.Json uses it and matches parameter names to JSON names case-insensitively; with several, mark one [JsonConstructor]. required members are enforced — a payload missing one throws JsonException rather than quietly leaving a default behind, which is the behaviour you want for a field you cannot proceed without.
Reading JSON you do not have a class for
| Tool | Shape | Use when |
|---|---|---|
JsonSerializer.Deserialize<T> | Your own type | The schema is known — the default choice |
JsonNode / JsonObject | Mutable tree | You must patch or build JSON by hand |
JsonDocument / JsonElement | Read-only, pooled | Fast inspection of a few fields |
Utf8JsonReader | Forward-only struct | Millions of documents, zero allocation |
JsonDocument rents its buffers from a pool, so it is IDisposable: wrap it in using, and never let a JsonElement escape that scope without calling .Clone(). JsonNode has no such rule and is the friendlier tool for anything you intend to modify.
Polymorphism, safely
Serializing a Shape reference that actually holds a Circle writes only the Shape members unless you declare the family:
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Circle), "circle")]
[JsonDerivedType(typeof(Square), "square")]
abstract class Shape { public string Colour { get; set; } = "black"; }
The discriminator is a closed list of names you chose, not a .NET type name. That is the whole security point. Newtonsoft's TypeNameHandling.All writes real assembly-qualified type names and instantiates whatever it reads back, which turns any untrusted payload into a way to construct arbitrary types in your process — a well-documented remote-code-execution route. Never enable it on data you did not produce.
Streaming, and the async overloads
Serialize returns a string, which means the whole document sits in memory. For anything large, hand the serializer a stream:
await using var stream = File.Create("orders.json");
await JsonSerializer.SerializeAsync(stream, orders, Json);
// And reading back one element at a time, never the whole array:
await foreach (Order? o in JsonSerializer.DeserializeAsyncEnumerable<Order>(input, Json))
Console.WriteLine(o!.Reference);
DeserializeAsyncEnumerable yields items as bytes arrive, so a 2 GB array of orders costs one order's worth of memory. It pairs naturally with an HTTP response stream from HttpClient.GetStreamAsync.
Source generation
Reflection-based serialization needs runtime code generation, which Native AOT and trimming forbid. A partial context class moves the work to compile time:
[JsonSerializable(typeof(Order))]
partial class OrderContext : JsonSerializerContext { }
string json = JsonSerializer.Serialize(order, OrderContext.Default.Order);
Startup gets faster, the trimmer can see exactly which members are used, and the type is checked at build time instead of on the first request.
The Newtonsoft comparison
System.Text.Json | Newtonsoft.Json | |
|---|---|---|
| Ships with | .NET itself | NuGet package |
| Speed and allocation | Faster, UTF-8 native | Slower, UTF-16 internally |
| Default strictness | Strict | Forgiving |
DataTable, dynamic, ISerializable | Not supported | Supported |
| Native AOT / trimming | Yes, via source generation | No |
New code should default to System.Text.Json. Newtonsoft remains the right answer for its long tail of features and for existing code whose behaviour you must not change.
Real World Example: An Order Coming Off the Wire
A warehouse posts orders to your service. The payload is camelCase, the status is a word rather than a number, delivery details are optional, and the warehouse keeps adding fields you have not modelled yet. All of that is normal, and all of it is configuration rather than code.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
enum Status { Pending, Shipped, Cancelled }
record Address(string City, string Postcode);
record Order
{
public required string Reference { get; init; }
public Status Status { get; init; }
public decimal Total { get; init; }
public Address? DeliverTo { get; init; }
public List<string> Lines { get; init; } = new();
[JsonExtensionData] // catch what we have not modelled
public Dictionary<string, JsonElement>? Extra { get; init; }
}
class Program
{
// One instance, reused: it caches the metadata for every type it sees.
static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() }
};
static void Main()
{
string incoming = """
{
"reference": "ORD-1001",
"status": "Shipped",
"total": 149.5,
"deliverTo": { "city": "Leeds", "postcode": "LS1 4AP" },
"lines": ["desk", "lamp"],
"warehouseNote": "fragile"
}
""";
Order order = JsonSerializer.Deserialize<Order>(incoming, Json)!;
Console.WriteLine(order.Reference + " " + order.Status + " " + order.Total);
Console.WriteLine("city: " + (order.DeliverTo?.City ?? "n/a") + ", lines: " + order.Lines.Count);
Console.WriteLine("unmapped: " + string.Join(",", order.Extra!.Keys));
// Cancel it and send it back out.
Order updated = order with { Status = Status.Cancelled, DeliverTo = null };
Console.WriteLine(JsonSerializer.Serialize(updated, Json));
}
}
Output:
ORD-1001 Shipped 149.5
city: Leeds, lines: 2
unmapped: warehouseNote
{"reference":"ORD-1001","status":"Cancelled","total":149.5,"lines":["desk","lamp"],"warehouseNote":"fragile"}
Read the last line carefully, because four separate settings are visible in it. deliverTo is gone rather than null, because WhenWritingNull dropped it. status is the word Cancelled, because the enum converter is registered — without it you would be shipping 2, and every consumer would have to hard-code your enum's numbering. Names are camelCase without a single attribute, because the web defaults said so. And warehouseNote — a field this program has never heard of — round-tripped intact from the extension-data dictionary.
That last point is what makes a service survive a partner's deploy. Fields you have not modelled land in Extra instead of vanishing, so an order you forward or store keeps everything it arrived with. Combine it with required on Reference and you get a useful split: the fields you truly depend on fail loudly when absent, and everything else is carried without ceremony.
Common Mistakes
- Creating a new
JsonSerializerOptionson every call. Each instance rebuilds the reflection cache for every type it touches. Store one in astatic readonlyfield. - Assuming case-insensitive matching.
{"name":"Chair"}leavesNamenull by default and throws nothing. UseJsonSerializerDefaults.Webor setPropertyNameCaseInsensitive. - Expecting fields to serialize. Only properties are included unless you set
IncludeFields = trueor add[JsonInclude]. A public field silently disappears. - Shipping enums as numbers by accident. Without
JsonStringEnumConverter, consumers depend on your enum's numeric values, and reordering members becomes a breaking change. - Serializing entities with navigation properties. A parent that references its children which reference the parent throws on the cycle, and a lazy-loading proxy can drag half the database into the payload. Map to a DTO instead.
- Letting a
JsonElementoutlive itsJsonDocument. Once the document is disposed its pooled buffer is recycled, and the element reads whatever landed there next.Clone()before it escapes. - Enabling
TypeNameHandlingin Newtonsoft to get polymorphism. It instantiates types named in the payload. Use[JsonDerivedType]with discriminators you control. - Building the string first for large payloads.
Serializeon a 200 MB collection allocates a 200 MB string, likely on the large object heap. UseSerializeAsyncto a stream.
Best Practices
- Start from
new JsonSerializerOptions(JsonSerializerDefaults.Web)for anything HTTP, so client and server agree without per-property attributes. - Keep exactly one options instance per configuration,
static readonly, and treat it as immutable — it is, after first use. - Serialize DTOs or records, never your EF Core entities. The wire shape and the storage shape change for different reasons.
- Mark the fields you cannot proceed without as
required, and let deserialization fail loudly instead of handing you a half-built object. - Use
[JsonPropertyName]when the wire name is fixed by someone else, and a naming policy when it is merely a convention. - Add
[JsonExtensionData]to types you forward or store, so a partner's new field is carried rather than dropped. - Prefer
SerializeAsync/DeserializeAsyncEnumerableover strings for collections, files and HTTP bodies of unknown size. - Turn on source generation for AOT, trimmed or startup-sensitive apps, and get build-time errors instead of first-request ones.
Practice Exercises
- Define a
Bookrecord withTitle,Author, anintYearand adecimalPrice. Serialize one instance with default options and again with camelCase plusWriteIndented, and print both. - Take the payload
{"title":"Dune","author":"Herbert","year":1965,"price":"12.99"}— note the quoted number — and deserialize it successfully by configuringNumberHandlingand case-insensitive matching. - Add a
Genreenum toBookand prove with two serializations that it writes as a number by default and as a word onceJsonStringEnumConverteris registered. - Write 5,000
Bookrecords to a file withSerializeAsync, then read them back withDeserializeAsyncEnumerable, counting them as they arrive without ever holding the whole list in memory.