Your agent's new C# union deserialises half a payload as a valid case: pin it with a JSON corpus
System.Text.Json in .NET 11 reads unions natively, but two object-shaped cases throw until you add a classifier, and the classifier accepts a payload with a field missing. Eight xUnit tests close both gaps, and they work with any agent.

An agent adds a union PaymentMethod(Card, BankTransfer) to your API, wires it into a minimal API endpoint, and the happy-path tests pass. A client then posts {"brand":"visa"}, a card with no number, and the endpoint hands your handler a Card whose Last4 is null. Nothing threw, and nothing logged. The union did what it was told.
That’s the behaviour in .NET 11, which shipped on 10 November 2026 with C# 15. System.Text.Json reads and writes unions without a custom converter, but the rules for choosing a case are narrower than they look, and the fix for the first problem creates the second. This piece builds a small JSON corpus that pins all of it. The tests are plain xUnit, so they work whichever agent wrote the union, and they take about 15 minutes to add to a project. The compiler side of unions, including the exhaustiveness warning, is in the earlier post . This one covers the wire.
What System.Text.Json does with a union
Microsoft’s ASP.NET Core write-up
(10 September 2026) describes the contract. A union serialises as its active case alone: no envelope, no $type, no discriminator. A Circle case writes as {"radius":2}, and an int case writes as 42. On read, the serialiser picks the case from the JSON token type. If the cases have different token types, that’s unambiguous. If two cases share one, it isn’t.
The same post lists the limits that matter for an API. Unions work as request bodies and return types in minimal APIs and MVC controllers, but not in query strings, route values, headers or form fields, because those sources can’t reliably choose a case. So this is a body-only feature. An agent that puts a union on a query parameter is asking for something the framework doesn’t do.
Here’s the shape of what actually happens. With SDK 11.0.100 and a net11.0 console project, no LangVersion set:
public record Circle(double Radius);
public record Square(double Side);
public union Shape(Circle, Square);
public union IntOrString(int, string);
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web);
Console.WriteLine(JsonSerializer.Serialize<Shape>(new Circle(2), web));
Console.WriteLine(JsonSerializer.Serialize<IntOrString>(42, web));
Run it and it prints:
{"radius":2}
42
Writing is the easy half. Reading is where the agent’s tests usually stop checking.
Failure one: two object cases are ambiguous
Add the card and bank transfer cases, both records, and read one back:
public record Card(string Brand, string Last4);
public record BankTransfer(string Iban, string Reference);
public union PaymentMethod(Card, BankTransfer);
JsonSerializer.Deserialize<PaymentMethod>("""{"brand":"visa","last4":"4242"}""", web);
That throws, and the message is clear about why:
JsonException: JSON value type 'Object' is ambiguous for union type 'PaymentMethod' because multiple case types can use this value type. Specify a custom type classifier to support deserialization.
This is the good failure, because it’s loud. An agent that runs the endpoint once sees it and reaches for the fix the message suggests, which is a classifier. The built-in one is JsonUnionTypeStructuralClassifier, applied with an attribute:
[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union PaymentMethod(Card, BankTransfer);
The classifier picks the case by property names. Microsoft’s post notes the costs: it scans the object before deserialising, so the work grows with payload size, and renaming a property can change which case matches or make it ambiguous. For new contracts the post recommends a closed hierarchy with a discriminator instead. That’s the better design when you control both ends. Unions earn their place when you’re modelling a shape that already exists on the wire, or when the case types are unrelated and a shared base class would be an invention.
Failure two: the classifier accepts a partial payload
With the classifier attached, the first two payloads work. A Card JSON body gives a Card, a bank transfer body gives a BankTransfer. Then the probe that matters:
var r = JsonSerializer.Deserialize<PaymentMethod>("""{"brand":"visa"}""", web);
Console.WriteLine(r.Value);
Card { Brand = visa, Last4 = }
It matched Card on the one property it recognised and left Last4 as null. The structural classifier decides the case; it doesn’t validate it. Under <Nullable>enable</Nullable> the compiler thinks Last4 can’t be null, so every downstream switch arm that reads card.Last4.Length is now a latent NullReferenceException.
The fix is the one the strict-deserialisation post uses for ordinary DTOs: mark the properties JsonRequired. What makes it worth knowing here is that the classifier respects it. A body that doesn’t satisfy any case’s required members now fails classification instead of landing in the nearest case:
public record Card(
[property: JsonRequired] string Brand,
[property: JsonRequired] string Last4);
public record BankTransfer(
[property: JsonRequired] string Iban,
[property: JsonRequired] string Reference);
[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union PaymentMethod(Card, BankTransfer);
With that in place, {"brand":"visa"} throws:
JsonException: The custom type classifier for union type 'PaymentMethod' returned null for JSON token type 'StartObject'.
The exception is a JsonException, which a body binder treats as a bad request, so the handler shouldn’t run (that mapping is standard ASP.NET Core behaviour, not something the tests below exercise). The strict wire contract post
covers the other half of that, rejecting unknown members, which these tests don’t repeat.
The corpus
Put the declarations above in a test project (dotnet new xunit -f net11.0, then add the file below) or reference them from the real one. The tests assert the round trip for each case and a list of payloads that must be refused:
using System.Text.Json;
using System.Text.Json.Serialization;
public class PaymentMethodJsonTests
{
static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web);
[Fact]
public void Card_round_trips_as_its_own_shape()
{
PaymentMethod original = new Card("visa", "4242");
var json = JsonSerializer.Serialize(original, Web);
Assert.Equal("""{"brand":"visa","last4":"4242"}""", json);
Assert.IsType<Card>(JsonSerializer.Deserialize<PaymentMethod>(json, Web).Value);
}
[Fact]
public void BankTransfer_round_trips_as_its_own_shape()
{
PaymentMethod original = new BankTransfer("GB00TEST", "inv-7");
var json = JsonSerializer.Serialize(original, Web);
Assert.IsType<BankTransfer>(JsonSerializer.Deserialize<PaymentMethod>(json, Web).Value);
}
[Theory]
[InlineData("""{"brand":"visa"}""")]
[InlineData("""{"iban":"GB00TEST","last4":"4242"}""")]
[InlineData("""{"brand":"visa","last4":"4242","iban":"GB00TEST","reference":"r"}""")]
[InlineData("""{}""")]
[InlineData("""[]""")]
public void Payloads_that_match_no_single_case_are_rejected(string json)
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<PaymentMethod>(json, Web));
}
[Fact]
public void Null_payload_never_reaches_a_handler_as_a_valid_case()
{
var result = JsonSerializer.Deserialize<PaymentMethod>("null", Web);
Assert.Null(result.Value);
}
}
Run dotnet test. Without the JsonRequired attributes, the first rejection case fails with “No exception was thrown” and the other seven pass. With them:
Passed! - Failed: 0, Passed: 8, Skipped: 0, Total: 8
The rejection list is the part to read in review. Each line is a way a client, or a future agent edit, can send something that is almost a case. The mixed payload with a card field and a bank field, and the one carrying both full shapes, are the interesting ones: both are refused in the run above, which is the behaviour you want. It’s observed classifier behaviour and not a documented guarantee, so keep the tests as the thing that notices if it changes.
The null test is a warning, not a pass
The last test asserts something uncomfortable. Deserialising the JSON literal null into a struct union doesn’t throw; it gives a union whose Value is null. Serialising default(PaymentMethod) writes null too, so a default-initialised union survives a round trip as nothing at all.
That matches what the C# docs
say about default unions: their contents are null, a switch with no null arm throws SwitchExpressionException on one, and the compiler may not warn when all the case types are non-nullable. So a handler that takes a PaymentMethod parameter from a body can still receive an empty one if the client sends null. Either add a null arm that returns a 400 result, or reject the value at the top of the handler:
app.MapPost("/payments", (PaymentMethod method) => method switch
{
Card c => Results.Ok($"card ending {c.Last4}"),
BankTransfer b => Results.Ok($"transfer {b.Reference}"),
null => Results.BadRequest("A payment method is required."),
});
The null arm is also the right one for a different reason, which the docs give: a discard arm would silence the warning when someone adds a third case, and a null arm keeps it.
The string that matches two cases
One more probe is worth keeping in the corpus whenever a union has both a number and a string case. Under JsonSerializerDefaults.Web, which is what minimal APIs and MVC use, numbers may be read from strings. So a JSON string can match either int or string:
JsonSerializer.Deserialize<IntOrString>("\"hi\"", web); // Web defaults
Console.WriteLine(JsonSerializer.Deserialize<IntOrString>("\"hi\"")!.Value); // plain defaults
JsonException: JSON value type 'String' is ambiguous for union type 'IntOrString' because multiple case types can use this value type. ...
hi
The first call uses Web defaults and throws (output shortened); the second uses plain defaults and prints the string. Same union, same payload, different options object. The ASP.NET Core post flags this and says it needs an explicit custom classification. The practical rule is that a union with int and string cases can pass a unit test written against default options and fail in the real pipeline, so build the options in the test the way the app builds them. If the app calls ConfigureHttpJsonOptions, share one options instance between the app and the tests.
Prompting for it
The agent will write the union and the happy-path test on its own. What it won’t do unprompted is the rejection list. A prompt that gets it:
Add union PaymentMethod(Card, BankTransfer) for the POST /payments body.
Before implementing, write xUnit tests that use the same JsonSerializerOptions
the app uses. Include a round trip for each case and a [Theory] of payloads that
must throw JsonException: a card missing a field, a payload mixing fields from
two cases, an empty object, an array, and a body that is too long. Then make the
tests pass. Do not edit the tests to make them pass.
Nothing in that depends on one tool. It needs a coding agent that can read files and run dotnet test, and a human who reads the rejection list.
Where this doesn’t help
The corpus covers shape, not meaning. {"brand":"visa","last4":"not digits"} is a valid Card; range and format rules still belong in a validation layer. It also only covers bodies. Microsoft says non-body binding for unions is still under exploration, so a union that an agent routes through a query string or a header won’t bind at all, and no JSON test will tell you.
For a contract you’re designing from scratch, skip the structural classifier. A closed record hierarchy with a discriminator, the option the same post recommends, turns “which case is this” into an explicit field instead of an inference from property names, and it doesn’t care whether a client renames reference.
To start now, take any union an agent has added this month, copy its shape into a test project, and write the five rejection payloads. If one of them is accepted, that’s the bug.