The dangerous default is not a warning, it is a value
A generated class file under #nullable enable compiles cleanly, which is exactly what makes the next problem easy to miss:
#nullable enable
public class Order
{
public long Id { get; set; }
public string Status { get; set; } = string.Empty;
public decimal Total { get; set; }
public string? CouponCode { get; set; }
}Every non-nullable reference property has an initialiser, so the compiler has nothing to complain about. Then the endpoint omits status, and the deserialiser simply does not touch the property:
// The server omitted "status" entirely.
var order = JsonSerializer.Deserialize<Order>(json)!;
// Reads as "", the initialiser value. This branch is wrong:
// it treats "the field was never sent" as "the server sent an empty string".
if (order.Status == "")
{
Console.WriteLine("no status");
}Three different documents — key absent, key present as "", key present with text — produce two indistinguishable outcomes. The initialiser that silenced CS8618 also created a value that looks like data. This is the C# face of a problem every typed language in this series runs into: the generated model is a hypothesis about the payload, and the default is the part of the hypothesis that fails silently.
required is the runtime half of the contract
Nullable reference types are a compile-time analysis of your code. They say nothing about what a JSON document contains, and JsonSerializer does not consult them when binding. The required modifier is the part that System.Text.Json does enforce:
#nullable enable
public class Order
{
public long Id { get; set; }
public required string Status { get; set; }
public decimal Total { get; set; }
public string? CouponCode { get; set; }
}With that modifier, a payload missing status fails with a JsonException that names the missing properties, instead of handing you an object that quietly answers "". That is the difference between a bug you find in a test and a bug you find in a report — and it is why required, not the initialiser, is what the field actually needed.
- Use required for guaranteed keys. Anything the API promises to send on every response. The failure is then loud and immediate.
- Use string? for genuinely optional keys. Then
nullmeans “not sent” and the compiler makes you check before dereferencing — which is the whole point. - Do not mix them on one property. A nullable property with a non-null default is the combination that produces the invisible empty string.
The generator emits required-free classes on purpose: it cannot tell a key that is always present from a key it happened to see in every sample. Adding the modifier is a one-word edit per field, and it is the highest value edit in the file.
Binding is exact by default, and casing counts
System.Text.Json matches property names with StringComparison.Ordinal: total and Total are different names. Since the C# convention is PascalCase and JSON keys are usually camelCase or snake_case, the exact-spelling rule surprises people on the first response they try:
| JSON key | Property | Default options | [JsonPropertyName] | CamelCase policy |
|---|---|---|---|---|
| total | Total | Not bound — property stays 0 | Bound | Bound by CamelCase policy |
| order_id | OrderId | Not bound — property stays 0 | Bound | Not bound by CamelCase; needs SnakeCaseLower (.NET 8+) or a custom policy |
| Total | Total | Bound | Bound | Bound |
| couponCode | CouponCode | Not bound — stays null | Bound | Bound |
The middle column of the first row is the failure worth recognising: nothing throws, the property keeps its default, and the object looks valid. A policy is the tidiest fix for a whole API surface, but it only covers the case-convention mismatch — snake_case needs .NET 8’s SnakeCaseLower, and irregular keys need the attribute regardless. Emitting [JsonPropertyName] wherever the spelling differs is the version that works on every supported runtime and survives being copied into a single file.
A mixed-type field is a JsonElement with a lifetime
When a key holds a string in one record and a number in another, no CLR type fits and the generated class uses object. At runtime that property is not a dictionary and not a string: it is a JsonElement, a view into the JsonDocument that produced it.
public class Order
{
public long Id { get; set; }
// object becomes JsonElement at runtime: a live view into a document.
public object? Metadata { get; set; }
}
using var doc = JsonDocument.Parse(json);
var order = new Order
{
Id = 1,
Metadata = doc.RootElement.GetProperty("metadata"),
};
// doc is disposed at the end of the using block...
order.Metadata.ToString(); // ObjectDisposedException: The JsonDocument has been disposed.The exception has nothing to do with serialisation — the value is a pointer into memory that was already returned to a pool. Two fixes, one of which is a design fix:
// Detach the value from its document before storing it.
Metadata = doc.RootElement.GetProperty("metadata").Clone();
// Or model it properly, which skips JsonElement altogether.
public JsonNode? Metadata { get; set; }Clone() copies the subtree out of the document so it survives disposal, at the cost of a hidden allocation per value. Using JsonNode is the better answer when the data is genuinely open-ended: it is a mutable tree that owns its values, so there is no document to outlive. When the shape is known, the real fix is a class the generator could not infer from two disagreeing samples.
Positional records skip the initialiser, and the check
A record is the right shape for a read-only response model, and one line replaces a whole class. It also removes the initialiser that was hiding the missing-key problem — not by solving it, but by moving it:
// Positional record: compact, but every parameter is filled with default(T)
// when its key is absent — including the ones annotated as non-nullable.
public record Order(long Id, string Status, decimal Total, string? CouponCode);A record component has no initialiser, so an absent key passes default(T) to the constructor: null for Status even though the parameter is annotated non-nullable, 0 for Total. Nullable reference types do not run inside deserialisation, so the annotation is a promise the constructor cannot keep. The same rules as before apply — required for guaranteed keys, nullable types for the rest — and a record gives you one extra option: a validating constructor that rejects a null where the contract says there cannot be one.
Round-trip with a real payload
The test that catches binding, casing and numeric mistakes in one pass: parse the captured response, serialize the object back, and compare the two trees.
[Fact]
public void RoundTripsThePayload()
{
const string raw = """
{ "id": 84126, "status": "paid", "total": 19.50, "coupon_code": null }
""";
var order = JsonSerializer.Deserialize<Order>(raw)!;
Assert.Equal("paid", order.Status);
Assert.Null(order.CouponCode);
var before = JsonNode.Parse(raw)!;
var after = JsonSerializer.SerializeToNode(order)!;
// DeepEquals compares structure and values, not formatting.
Assert.True(JsonNode.DeepEquals(before, after));
}JsonNode.DeepEquals compares structure and values while ignoring formatting, so a reformatted response does not fail the test. What it does catch: a property that never bound (its key disappears from the output), a value that changed type, and a field that serialised as the wrong name. Keep one captured response per endpoint — the file becomes a contract that fails the moment the API changes shape. For the same technique in other languages, see the Java guide and the Go guide.