diff --git a/src/main/java/io/swagger/codegen/v3/generators/SchemaHandler.java b/src/main/java/io/swagger/codegen/v3/generators/SchemaHandler.java index cfcf7e60a6..e4e908f579 100644 --- a/src/main/java/io/swagger/codegen/v3/generators/SchemaHandler.java +++ b/src/main/java/io/swagger/codegen/v3/generators/SchemaHandler.java @@ -175,7 +175,17 @@ protected void addInterfaces(List schemas, CodegenModel codegenModel, Ma continue; } final String schemaName = ref.substring(ref.lastIndexOf("/") + 1); - this.addInterfaceModel(allModels.get(codegenConfig.toModelName(schemaName)), codegenModel); + + final CodegenModel model = allModels.get(codegenConfig.toModelName(schemaName)); + this.addInterfaceModel(model, codegenModel); + + boolean subTypeAdded = false; + if (codegenModel.getSubTypes() != null) { + subTypeAdded = codegenModel.getSubTypes().stream().anyMatch(existingSubType -> existingSubType.classname.equalsIgnoreCase(model.classname)); + } + if (!subTypeAdded) { + codegenModel.addSubType(model); + } } } diff --git a/src/main/resources/handlebars/Java/interface.mustache b/src/main/resources/handlebars/Java/interface.mustache index becc0c5549..bd8ff9a735 100644 --- a/src/main/resources/handlebars/Java/interface.mustache +++ b/src/main/resources/handlebars/Java/interface.mustache @@ -1,6 +1,21 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +{{/jackson}} /** * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} */ +{{#jackson}} +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, + include = JsonTypeInfo.As.PROPERTY, + property = "type") +@JsonSubTypes({ + {{#subTypes}} + @JsonSubTypes.Type(value = {{classname}}.class, name = "{{classname}}"){{^@last}},{{/@last}} + {{/subTypes}} +}) +{{/jackson}} public interface {{{classname}}} { }