Skip to content

Consider the @JsonSubTypes for generating the discriminator mapping #3411

Open
@SabhtarshaMojo

Description

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,

@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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions