OpenAPI oneOf guide
Round-trip a C# oneOf with a discriminator.
Generate a discriminated union from two named OpenAPI schemas. Follow a card and a bank payment through System.Text.Json and see which invalid inputs it rejects.
Program.csvar method = JsonSerializer.Deserialize<PaymentMethodUnion>(json);{"kind":"card","last4":"4242"}Serialized through the union with one kind property and read back equal.Run it in your repository
The companion contains the OpenAPI input, generated sources, assertions and reproduction script.
Define the union
PaymentMethod is a oneOf of CardPayment and BankPayment with an explicit kind mapping.
Generate the models
Pin the tool and compile the generated interface and records with .NET SDK 10.0.105.
Exercise four payloads
Both payments round-trip with one kind property. An unknown kind and a card without last4 must throw JsonException.
bash verify.sh /tmp/metaengine-oneof-checkRead the complete walkthrough
An API can return more than one shape from the same field. A payment method might contain a card's last four digits or a bank account reference. A useful C# client preserves that choice through deserialization, application code and serialization back to JSON. A oneOf declaration alone does not prove that round-trip works.
This guide generates a discriminated union with the public MetaEngine C# tool and tests the actual generated models. The complete companion uses synthetic payment data, includes no engine source, and keeps the generated output unmodified.
The case this guide covers
The union has two named component schemas, CardPayment and BankPayment, and an explicit discriminator mapping on a kind property. Every claim below applies to that shape. Inline variants without names, or variants that overlap in shape and carry no discriminator, are separate cases that this guide does not test.
Describe how the wire format selects a shape
The complete OpenAPI 3.0.3 input is api.json in the companion. It defines PaymentMethod as follows.
{
"oneOf": [
{ "$ref": "#/components/schemas/CardPayment" },
{ "$ref": "#/components/schemas/BankPayment" }
],
"discriminator": {
"propertyName": "kind",
"mapping": {
"card": "#/components/schemas/CardPayment",
"bank": "#/components/schemas/BankPayment"
}
}
}
CardPayment requires string kind and last4. BankPayment requires string kind and iban. The wire inputs are {"kind":"card","last4":"4242"} and {"kind":"bank","iban":"EXAMPLE-IBAN"}. The explicit mapping keeps the public JSON values independent of C# type names. The fixture has no HTTP operations because the behavior under test is model serialization.
Generate the public models
Use .NET SDK 10.0.105, pinned by the companion's global.json, and tool 1.0.2.
dotnet tool install --tool-path ./tools MetaEngine.CSharp.OpenApi.HttpClient.Tool --version 1.0.2
DOTNET_ROLL_FORWARD=Major ./tools/metaengine-openapi-csharp-httpclient api.json ./Generated Guide.Methods
Run these commands from the companion directory. The tool targets .NET 8, so DOTNET_ROLL_FORWARD=Major lets it run on the verified .NET 10 runtime. The reproduction script below keeps the tool installation and build output outside your checkout.
The generated union is an interface decorated with System.Text.Json metadata.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(CardPayment), "card")]
[JsonDerivedType(typeof(BankPayment), "bank")]
public interface PaymentMethodUnion { }
The generated CardPayment is a record implementing PaymentMethodUnion with a required Last4 property mapped to last4. BankPayment similarly exposes required Iban. Neither record has a Kind property, because the serializer owns the discriminator metadata in this output. A second property with the same JSON name would collide with that metadata and break the contract this example verifies.
Deserialize and serialize through the union
In the companion's Program.cs, deserialize with the union type so the discriminator can choose the record.
var card = JsonSerializer.Deserialize<PaymentMethodUnion>(cardJson);
if (card is not CardPayment { Last4: "4242" })
throw new Exception("Unexpected payment method.");
var serialized = JsonSerializer.Serialize<PaymentMethodUnion>(card);
var roundTrip = JsonSerializer.Deserialize<PaymentMethodUnion>(serialized);
The generic union type on serialization selects the generated polymorphic contract. Calling Serialize with a concrete record type is a different operation and the example does not demonstrate it. Microsoft's polymorphism documentation explains how declared types, derived types and discriminator metadata relate.
The executable example checks both runtime types, counts exactly one kind property in each serialized JSON object, and compares the reconstructed records with their originals. It also expects JsonException for an unknown discriminator (cash) and for a card missing the required last4. Both exceptions are intentional assertions and the process fails if either input is accepted.
Run the exact reproduction
Unzip the companion, open the extracted folder in a terminal, and choose a new absolute scratch path.
bash verify.sh /tmp/metaengine-oneof-check
The script refuses an existing directory, installs the pinned tool, regenerates the source into scratch, compares every generated file with the checked-in output, compiles the project and runs all four cases. The observed output is as follows.
PASS CardPayment round-trip: {"kind":"card","last4":"4242"}
PASS BankPayment round-trip: {"kind":"bank","iban":"EXAMPLE-IBAN"}
PASS rejected {"kind":"cash"}
PASS rejected {"kind":"card"}
This result covers the explicit two-branch discriminator contract on the pinned tool and runtime. It says nothing about untagged oneOf shapes, inline variants, arbitrary allOf graphs, missing discriminators or other schema constraints. The inputs place the discriminator first, so an API that sends it later needs its own compatibility check against your serializer settings. A required string is also not an IBAN validator.
To inspect your own model, open the OpenAPI to C# converter. For CLI options and installation choices, use the C# HttpClient package page. Keep one round-trip test per branch and add another when the API adds a discriminator value.