我将使用Maven插件swagger-codegen-maven-plugin版本2.2.3生成Java类。这是我的pom.xml文件的配置:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${basedir}/src/main/resources/swagger/project.yaml</inputSpec>
                <language>java</language>
                <configOptions>
                    <sourceFolder>src/gen/java/main</sourceFolder>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>


我的project.yaml文件包含以下内容:

definitions:
    Parent:
        type: "object"
        discriminator: "type"
        required:
            - type
        properties:
            id:
                type: "integer"
                format: "int64"
            code:
                type: "string"
   ChildA:
       allOf:
           - $ref: "#/definitions/Parent"
           - properties:
                 attributeA:
                     type: "string"
   ChildB:
       allOf:
           - $ref: "#/definitions/Parent"
           - properties:
                 attributeB:
                     type: "string"


生成所有3个类,然后我要使用Web服务创建ChildAChildB。所以我的方法是:

@POST
public Response createChild(@WebParam Parent parent) {
    ...
}


使用Postman,我发送了以下json以创建ChildA实例:

{
    "code": "child-a",
    "attributeA": "value"
}


发生以下异常:

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "attributeA" (class io.swagger.client.model.Parent), not marked as ignorable (2 known properties: "code", "id"])
    at [Source: io.undertow.servlet.spec.ServletInputStreamImpl@1df2f416; line: 3, column: 17] (through reference chain: io.swagger.client.model.Parent["attributeA"])


我在几个地方的Parent类中都需要阅读一些注释,例如:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @Type(value = ChildA.class, name = "ChildA"),
    @Type(value = ChildB.class, name = "ChildB" ) })


但是我不知道如何修改我的Yaml文件来添加这些注释。有人可以帮我吗?

最佳答案

我找到了解决方案(不幸的是,没有慷慨的文档)。在我的pom.xml中的插件配置中,缺少<library>resteasy</library>。现在的完整配置为:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${basedir}/src/main/resources/swagger/project.yaml</inputSpec>
                <language>java</language>
                <configOptions>
                    <sourceFolder>src/gen/java/main</sourceFolder>
                    <library>resteasy</library>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

07-24 09:38
查看更多