skip to content

With System.Text.Json's JsonSerializer, which naming and case-sensitivity defaults apply, and why should code reuse one JsonSerializerOptions instance?

level: middleimportance: must knowfreq 52%

answer

  1. names as declared
  2. exact-case matching on read
  3. Web preset differs
  4. per-instance metadata cache
  5. frozen after first use

basics

~20 s

JsonSerializer writes property names exactly as declared and matches them case-sensitively on read, silently skipping unmatched JSON. Each JsonSerializerOptions instance caches per-type metadata and becomes read-only after first use, so create one and share it.

solid answer

~40 s

With default options, `JsonSerializer` writes `InvoiceNumber` as `InvoiceNumber`, reads names case-sensitively and skips unknown JSON properties without error; it also writes enums as numbers, ignores fields and escapes non-ASCII characters. `JsonSerializerDefaults.Web` (also the `JsonSerializerOptions.Web` singleton since .NET 9) switches to camelCase, case-insensitive reads and numbers allowed in quotes; .NET 10 adds `JsonSerializerOptions.Strict`, which rejects unmapped and duplicate properties. Options should be reused because each instance holds the serializer's cache of converters and per-type contracts: a `new JsonSerializerOptions()` per call can redo that reflection work, which analyzer rule CA1869 flags. After first use an instance is frozen, and setting a property throws `InvalidOperationException`, so a shared `static readonly` instance is safe.

code

csharp · 24 lines
csharp
#:property PublishAot=false
using System.Text.Json;

var invoice = new Invoice { InvoiceNumber = "INV-2026-0042", Total = 125.50m };
Console.WriteLine(JsonSerializer.Serialize(invoice));
// {"InvoiceNumber":"INV-2026-0042","Total":125.50}
Console.WriteLine(JsonSerializer.Serialize(invoice, JsonSerializerOptions.Web));
// {"invoiceNumber":"INV-2026-0042","total":125.50}

const string partner = """{"invoiceNumber":"INV-7"}""";
Console.WriteLine(JsonSerializer.Deserialize<Invoice>(partner)!.InvoiceNumber ?? "(null)");  // (null)
Console.WriteLine(JsonSerializer.Deserialize<Invoice>(partner, JsonSerializerOptions.Web)!.InvoiceNumber); // INV-7

var options = new JsonSerializerOptions { WriteIndented = true };
JsonSerializer.Serialize(invoice, options);
try { options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }
catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
// This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization.

class Invoice
{
    public string? InvoiceNumber { get; set; }
    public decimal Total { get; set; }
}

go deeper

for a junior

Recall that names are written as declared, reads are case-sensitive, unknown properties are skipped, and the Web defaults switch to camelCase.

for a middle

Explain the per-instance metadata cache, why the instance freezes after first use, what CA1869 flags, and what the Web and Strict presets each change.

for a senior

Diagnose silent data loss from case mismatches and unmapped members, choose Strict or Disallow for partner contracts, and spot options created inside hot paths during review.

for a principal

Argue for one named options object per wire contract, owned and tested with that contract, rather than settings scattered across call sites.

## The general defaults **System.Text.Json** is the JSON serializer in the .NET base library. `JsonSerializer.Serialize` and `Deserialize` take an optional **`JsonSerializerOptions`**; when you pass none, they use the general defaults (`JsonSerializerDefaults.General`). The ones that surprise people: | Behaviour | Default | Effect on an invoice payload | |---|---|---| | `PropertyNamingPolicy` | `null` (names as declared) | `InvoiceNumber` is written as `"InvoiceNumber"` | | `PropertyNameCaseInsensitive` | `false` | `"invoiceNumber"` does not bind to `InvoiceNumber` | | `UnmappedMemberHandling` | `Skip` | Unknown or misspelled properties vanish silently | | `NumberHandling` | `Strict` | `"total":"9.99"` throws `JsonException` | | Enums | Numbers | `Status.Paid` is written as `1` | | `IncludeFields` | `false` | Public fields are ignored; only public properties count | | `Encoder` | Escapes non-ASCII and HTML-sensitive characters | `café` becomes `café` | The case-sensitive read and the silent skip combine into the classic bug: a partner sends camelCase, nothing throws, and every property stays at its default value. ## The Web and Strict presets - **`JsonSerializerDefaults.Web`** sets `PropertyNamingPolicy = JsonNamingPolicy.CamelCase`, `PropertyNameCaseInsensitive = true` and `NumberHandling = JsonNumberHandling.AllowReadingFromString`. Pass it to the constructor, `new JsonSerializerOptions(JsonSerializerDefaults.Web)`, or, since .NET 9, use the read-only singleton **`JsonSerializerOptions.Web`**. Web frameworks configure their own instance; how they do that is covered with ASP.NET Core. - **`JsonSerializerOptions.Strict`** (.NET 10) sets `UnmappedMemberHandling = Disallow`, turns `AllowDuplicateProperties` off, keeps case-sensitive binding and enables `RespectNullableAnnotations` and `RespectRequiredConstructorParameters`. An unknown property then fails with "The JSON property 'Extra' could not be mapped to any .NET member contained in type 'Invoice'." - **`JsonSerializerOptions.Default`** is the read-only singleton for the general defaults. ## Why one options instance should be shared Serializing a type for the first time is expensive: the serializer reflects over the type, chooses a **converter** for every property and builds a **`JsonTypeInfo`** contract. That metadata is cached on the options instance, so later calls with the same instance reuse it. 1. **A new instance means an empty cache.** Code that writes `JsonSerializer.Serialize(invoice, new JsonSerializerOptions { WriteIndented = true })` in a hot path can rebuild metadata on every call. Analyzer rule **CA1869**, "Cache and reuse 'JsonSerializerOptions' instances", flags a local instance used once as the `options` argument; the .NET 10 docs list it as enabled by default as a suggestion. 2. **The runtime softens, not removes, the cost.** The runtime source keeps a small shared table (up to 64 weakly held entries) of caching contexts for options instances with equivalent settings, so a fresh instance may find existing metadata. Treat that as a safety net: converters are compared by reference, so a `new JsonStringEnumConverter()` created per call defeats the match, and the table holds only 64 entries. 3. **Copying does not copy the cache.** `new JsonSerializerOptions(existing)` copies settings only; the docs state that the metadata cache of the original isn't copied. 4. **Used instances are frozen.** The first serialization makes the instance read-only (`IsReadOnly` becomes `true`), and changing any property afterwards throws `InvalidOperationException`: "This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization." You can also call `MakeReadOnly()` yourself. A frozen instance can be shared across threads. ## Other defaults that change behaviour - **Numbers**: `JsonNumberHandling.Strict` means `"total":"9.99"` fails; the Web defaults add `AllowReadingFromString`, which accepts it. Writing never quotes numbers unless you ask for `WriteAsString`. - **Enums**: written as their numeric value; `JsonStringEnumConverter` writes names. Registering it per call creates a new converter instance each time, which also defeats metadata sharing. - **Null handling**: null properties are written as `null`; `DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull` omits them. - **Read-only singletons**: `JsonSerializerOptions.Default`, `Web` and `Strict` are already frozen, so they can be passed anywhere but never modified; to change one setting, copy it with the copy constructor once and keep the copy. ## A practical pattern - Keep one `static readonly JsonSerializerOptions` per distinct configuration, for example `PartnerJson.Options`, and pass it everywhere that configuration applies. - Use `JsonSerializerOptions.Web` or `JsonSerializerOptions.Default` directly when the presets fit. - Decide naming per contract instead of per call site, and test both directions: serialize, then deserialize a payload written in the partner's actual casing. - Under trimming or Native AOT, the reflection path is replaced by source-generated contexts; that is a separate concern from reuse, but the same rule applies to the options object a context carries.

  • How do you make a misspelled partner property fail loudly instead of disappearing?
    Set `UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow` on your options, or use `JsonSerializerOptions.Strict` on .NET 10, which also disallows duplicate properties. Deserialization then throws `JsonException` naming the property that could not be mapped, instead of leaving the target member at its default.
  • Why might a partner see \u00E9 instead of é in your JSON, and how do you change it?
    The default encoder escapes every character outside the Basic Latin range. Set `Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)` to allow all language sets, or `JavaScriptEncoder.UnsafeRelaxedJsonEscaping` when the output is consumed as UTF-8 JSON and is never embedded in HTML or a script element.
  • Can you change an options instance after it has been used, for example to switch naming?
    No. Once used it is read-only and setters throw `InvalidOperationException`. Create a second instance for the second configuration, typically with the copy constructor `new JsonSerializerOptions(existing)`, and remember the copy starts with an empty metadata cache.

  • System.Text.Json camel-cases property names by default, like most web APIs.
  • Deserialization matches property names case-insensitively out of the box.
  • Creating a new JsonSerializerOptions per call is free because options are just settings.
  • An unknown JSON property makes Deserialize throw by default.
  • You can tweak a shared options instance at any time, for example per request.

Assumes .NET 10: the JsonSerializerOptions.Web singleton arrived in .NET 9 and the Strict preset in .NET 10; JsonSerializerDefaults.Web and the general defaults are available on every supported release.