Skip to content
DevTinyTools

Typing

JSON to C#: nullable, CS8618 and JsonElement

A generated C# class compiles under #nullable enable and binds the sample response, which makes it look finished. What it does not tell you is that a missing key leaves an initialised default in place, that a mixed-type field is a view into a document someone else may dispose, and that required means something the compiler can enforce if you ask it to.

9 min readTool: JSON to C#

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 null means “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:

Whether each JSON key binds under three configurations
JSON keyPropertyDefault options[JsonPropertyName]CamelCase policy
totalTotalNot bound — property stays 0BoundBound by CamelCase policy
order_idOrderIdNot bound — property stays 0BoundNot bound by CamelCase; needs SnakeCaseLower (.NET 8+) or a custom policy
TotalTotalBoundBoundBound
couponCodeCouponCodeNot bound — stays nullBoundBound

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.

Frequently asked questions

Why do properties have = string.Empty; in the generated file?
A non-nullable reference property that nobody initialises triggers compiler warning CS8618, and a project with warnings-as-errors turns that into a failed build. The initialiser silences it without changing behaviour on a successful bind, because System.Text.Json overwrites the value as soon as the key is present. The cost is that the default becomes indistinguishable from a real empty string when the key is absent — which is the subject of the first section of this guide.
How is required different from #nullable enable?
Nullable annotations are a compile-time promise about what your code does; they are not a runtime contract about what the JSON contains. The required modifier is the runtime half: System.Text.Json fails the deserialisation with a JsonException naming the missing properties instead of leaving a default in place. Use required for keys the API contract guarantees, and string? for the ones that may legitimately be absent.
Why does the JSON key total not bind to the property Total?
System.Text.Json matches property names case-sensitively by default, and Total is not total. Three things fix it: [JsonPropertyName("total")], JsonSerializerOptions.PropertyNameCaseInsensitive = true, or a naming policy such as JsonNamingPolicy.CamelCase. The policy is the tidiest for a whole API; the attribute is the only one that survives someone reading a single class in isolation, which is why generated files use it.
Does a naming policy handle snake_case keys too?
Only from .NET 8, which added JsonNamingPolicy.SnakeCaseLower and SnakeCaseUpper. On earlier versions a policy cannot express it, and the converter approach (a custom JsonNamingPolicy subclass) is more code than one attribute per field. The generated file therefore spells every divergent key out with [JsonPropertyName], which works on every supported version.
Why did my object-typed property throw 'The JsonDocument has been disposed'?
Because object does not become a dictionary or a string at runtime — when the source is a JSON object or array it becomes a JsonElement, which is a view into the JsonDocument that produced it. If that document was created with JsonDocument.Parse and disposed, every element obtained from it becomes invalid. Clone the element, store a JsonNode instead, or model the shape with a real class.
Should money be decimal or double?
decimal. double is a binary floating-point type, so 0.1 + 0.2 is not 0.3 and totals drift as soon as you sum them; decimal is base-10 and exact for the values money is written in. A generator emits double because a JSON number carries no units, but every field that holds a price should be changed to decimal by hand. If the payload sends prices as strings, add [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)].
Can a positional record be deserialised, and what happens to missing keys?
Yes, System.Text.Json binds records through their constructor. But a record parameter has no initialiser, so an absent key passes default(T) — null for a string, 0 for a long — even when the parameter is annotated non-nullable. Nullable reference types do not protect that path. If absence must fail, use required properties on a class, or validate the record after construction.
How are enums handled?
As numbers, by default: a JSON string will not bind to an enum property unless you register JsonStringEnumConverter. Add it once in JsonSerializerOptions.Converters and string values bind case-insensitively. An unknown string still throws, so if the API may add members later, either keep the field as a string or add a fallback member and a converter that maps unknown values to it.