Consider the @JsonSubTypes for generating the discriminator mapping

Author: SabhtarshaMojoCreated Jan 14, 2020Updated Sep 25, 2026
LabelsFeatureWorkaround availablebacklog

To generate the appropriate mapping for a discriminator of a parent class, we are required to add the discriminatorMapping property to @Schema, which is almost always redundant if the class already has a @JsonSubTypes annotation. As the discriminatorProperty is read from the @JsonTypeInfo.property can the discriminatorMappings also be read from the JsonSubTypes if available?

As a workaround, I have registered a CustomModelResolver and extended the method resolveDiscriminator as follows,

java
@Override
protected Discriminator resolveDiscriminator(JavaType type, ModelConverterContext context) {
	Discriminator discriminator = super.resolveDiscriminator(type, context);
	if (discriminator != null && discriminator.getPropertyName() != null &&
			(discriminator.getMapping() == null || discriminator.getMapping().isEmpty())) {
		JsonSubTypes jsonSubTypes = type.getRawClass().getDeclaredAnnotation(JsonSubTypes.class);
		if (jsonSubTypes != null) {
			Arrays.stream(jsonSubTypes.value()).forEach(subtype -> {
				discriminator.mapping(subtype.name(), RefUtils.constructRef(
						context.resolve(new AnnotatedType().type(subtype.value())).getName()));
			});
		}
	}
	return discriminator;
}

Additional Info: Using the swagger-maven-plugin v2.1.1 for generating the OAS files during the compile phase.

Source: swagger-api/swagger-core