首页 > 解决方案 > JsonTypeInfo.As.WRAPPER_OBJECT 是否有任何 swagger.json 标记?

问题描述

我有 2 个应用程序,应用程序 A 公开 API 供应用程序 B 使用。

应用程序 A 正在为应用程序 B 生成 swagger.json,应用程序 B 正在使用 swagger-codegen 生成模型代码。

在我的应用程序 A 中,它使用带有 WRAPPER_OBJECT 的多态杰克逊

@JsonTypeInfo (use = JsonTypeInfo.Id.NAME, include = 
JsonTypeInfo.As.WRAPPER_OBJECT, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = Dog.class, name = "doggy"), 
@JsonSubTypes.Type(value = Cat.class, name = "kitty")})
@ApiModel(subTypes = {Dog.class, Cat.class}, discriminator = "type")
public abstract class Animal {
}

@ApiModel(value = "kitty", parent = Animal.class)
public class Cat extends Animal {
    public int lives = 9;
}

@ApiModel(value = "doggy", parent = Animal.class)
public class Dog extends Animal {
    public double barkVolume = 100d;
}

期望 json 格式被包装。

{
    "kitty": {
        "lives": 9
    }
}

因此,当应用程序 A 使用 springfox 生成 swagger.json 时,它生成如下。

"Animal": {
    "type": "object",
    "discriminator": "type",
    "title": "Animal"
},
"doggy": {
    "title": "doggy",
    "allOf": [
        {
            "$ref": "#/definitions/Animal"
        },
        {
            "type": "object",
            "properties": {
                "barkVolume": {
                    "type": "number",
                    "format": "double"
                }
            },
            "title": "doggy"
        }
    ]
},
"kitty": {
    "title": "kitty",
    "allOf": [
        {
            "$ref": "#/definitions/Animal"
        },
        {
            "type": "object",
            "properties": {
                "lives": {
                    "type": "integer",
                    "format": "int32"
                }
            },
            "title": "kitty"
        }
    ]
}

但是当 swagger.json 让应用程序 B 生成代码时,问题就来了,生成的代码没有包装。

@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-08-28T12:54:58.555+08:00")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({@JsonSubTypes.Type(value = Kitty.class, name = "kitty"), @JsonSubTypes.Type(value = Doggy.class, name = "doggy"),})
public class Animal {
}

当生成如下 json 时。

{
    "type": "kitty",
    "lives": 9
}

我尝试检查 swagger-codegen 代码,似乎该代码始终将其生成为 JsonTypeInfo.As.PROPERTY。

我只是想知道 swagger.json 中可以定义杰克逊对象的任何选项是否可以生成为 WARPPER_OBJECT?

标签: javajsonjacksonswaggeropenapi

解决方案


推荐阅读