Skip to content

STJ: union vs. class asymmetry — missing JSON silently produces default(union) that crashes on serialize #4

Open

Description

@DeagleGross

STJ: union vs. class asymmetry — deserializing missing/unmatched JSON silently produces default(union), which then crashes on serialization

Is there an existing issue for this?

  • I have searched the existing issues

Description

When a JSON payload does not contain a value for a property of union type (either the key is absent or the entire body does not match the target shape), System.Text.Json silently constructs the containing record with default(union) for that property — same defaulting rule it applies to any other value type. No exception is thrown on read.

If the user then serializes that same instance back to JSON (e.g. a Minimal API endpoint that returns the parameter it received), the union converter throws:

System.Text.Json.JsonException: The union type 'TUnion' does not support null values. Path: $.Payload.
   at System.Text.Json.ThrowHelper.ThrowJsonException_UnionDoesNotAcceptNull(Type unionType)
   at System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.UnionMetadataBuilder`1.<>c__DisplayClass8_0.<>b__0(TUnion union)
   at System.Text.Json.Serialization.Converters.JsonUnionConverter`1.OnTryWrite(...)

The same dumb deserialize → serialize round-trip with an equivalent class record succeeds (all properties come back at their CLR defaults — 0, null, etc.). Unions are the only type where the silent-default rule on read produces an instance the serializer itself cannot write.

Reproducer

Union case (throws on write):

app.MapPost("/union/envelope", (UnionEnvelopeWithClassifier e) => e);

public record UnionEnvelopeWithClassifier(string CorrelationId, UnionIntStringWithClassifier Payload);

[JsonUnion(TypeClassifier = typeof(UnionIntStringClassifierFactory))]
public union UnionIntStringWithClassifier(int, string);
POST /union/envelope
Content-Type: application/json

{"name":"Whiskers"}

→ 500 (UnionDoesNotAcceptNull thrown at $.Payload during write).

Class case (silently round-trips):

app.MapPost("/weather", (Weather w) => w);

public class Weather
{
    public int TemperatureC { get; set; }
    public string? Summary { get; set; }
}
POST /weather
Content-Type: application/json

{"random":"lol"}

→ 200 {"temperatureC":0,"summary":null}.

Root cause

  1. STJ deserializes a containing record. For each constructor parameter or settable property whose JSON key is missing, STJ assigns the type's CLR default — null for reference types, default(T) for value types. This is uniform across all types.
  2. Unions compile to value types (structs) when any case is a value type, so a missing union property produces default(union) — a struct whose internal "selected case" tag is zero, i.e. no case set.
  3. default(union).Value returns null (the Value property is typed object? because a struct in default state cannot have a case payload).
  4. On serialization, JsonUnionConverter<TUnion>.OnTryWrite asks the metadata callback for the case value, receives null, sees that no declared case is null, and throws.

So the asymmetry is not in the deserializer — it is that JsonUnionConverter.OnTryWrite refuses to write a state that the deserializer is perfectly willing to construct.

Why this matters

  • The error appears far from the actual cause (POST body did not contain the key). Users see a write-side stack trace and have no obvious path to "you forgot to send payload".
  • The same code path with any other type succeeds. Users porting an existing model to use unions will not anticipate the regression.
  • Workarounds exist today (see below) but every one of them requires the user to know this trap is there.

Possible directions (pick one — listed from most to least invasive)

A. Symmetric read-side enforcement: reject "missing union property" during deserialization

The metadata builder for a containing type knows when a non-nullable union property had no matching JSON value (same hook JsonRequiredAttribute uses). Throw a clear JsonException at that point ("a value is required for property 'X' of union type 'TUnion'"). Restores symmetry: both sides reject the invalid state. Special-cases unions vs other structs.

B. Make unions implicitly required by default

Treat any non-nullable union property as [JsonRequired] unless explicitly opted out. Consistent with the union's own "no null" contract. Slightly more invasive but principled.

C. Status-quo + better error

Keep the throw, but improve the message to "union 'TUnion' has no active case — this commonly happens when the JSON did not contain a value for the property; consider [JsonRequired] or RespectRequiredConstructorParameters = true". Cheapest fix, no behavior change. Documentation entry on union deserialization gotchas in the cookbook.

D. Soften the write side: serialize default(union) as JSON null

Drop the UnionDoesNotAcceptNull throw when the source is default(union). Restores read/write symmetry with classes. But it sacrifices the union's invariant that the wire never carries null for a declared non-nullable union, and it bakes "default(union) ≡ null on the wire" into the protocol forever. Probably the wrong tradeoff for the type system, but the easiest UX win.

A combination is plausible — e.g. A for safety + C for the cases where the throw still fires.

Workarounds available today

  • JsonSerializerOptions.RespectRequiredConstructorParameters = true (global, .NET 9+).
  • [property: JsonRequired] on positional record parameters, [JsonRequired] on settable properties.
  • Declare the property as TUnion? and treat absence as null.
  • Run a custom validator (DataAnnotations, FluentValidation, MinimalApis.Extensions) before the handler.

Affected APIs

  • System.Text.Json.Serialization.Converters.JsonUnionConverter<T>.OnTryWrite
  • System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.UnionMetadataBuilder<T>
  • (depending on chosen fix) the metadata builder for containing types' missing-property handling

.NET version

11 (union types preview).

Related

  • aspnetcore: dotnet/aspnetcore#64599 — parent unions tracking issue.
  • aspnetcore: dotnet/aspnetcore#66542, #66543 — Minimal API union support; coverage in the PR for [JsonRequired] interaction confirmed the gap.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions