Skip to content

[API Proposal]: Expose polymorphic base type in JsonSchemaExporterContext #104046

@captainsafia

Description

@captainsafia

Background and motivation

For some derivations of JSON schema (particularly OpenAPI), it is necessary to modify the schemas generated by STJ for polymorphic types to correspond with the constraints of the spec. For example, OpenAPI prohibits subschemas that don't contain a type discriminator for a polymorphic type.

To aid implementers in complying with these constraints, a new property should be added to JsonSchemaExporterContext to support resolving the base type a derived type is being generated for. Currently, the only way to determine if we are generating a schema for a derived type is by inspecting the JsonPath. This doesn't give us any information about the base type that we are associated with.

API Proposal

namespace System.Text.Json.Schema;

public readonly struct JsonSchemaExporterContext
{
    // If specified, points to the polymorphic base type for which this derived schema is being generated.
+    public JsonTypeInfo? BaseTypeInfo { get; }
}

API Usage

JsonSchemaExporterOptions configuration = new()
{
	TransformSchemaNode = (context, schema) =>
	{
		if (context.BaseTypeInfo is {} baseType)
		{
			if (baseType.PolymorphismOptions.DerivedTypes.SingleOrDefault(type => type == baseType) is { } baseTypeInDerived)
			{
				if (baseTypeInDerived.TypeDiscriminator == null) return new JsonObject();
			}
		}
	}
};

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions