java - 如何在 Swagger 中描述多态端点?

标签 java spring jackson polymorphism swagger

我们使用Spring+Jackson(Java)。在我们的 API 中,我们可以将不同的对象发送到同一个端点。 例如

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = As.PROPERTY, 
    property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "dog"),
    @JsonSubTypes.Type(value = Cat.class, name = "cat")
})
public static class Animal {
}

@JsonTypeName("dog")
public static class Dog extends Animal {
    public double barkVolume;
}

@JsonTypeName("cat")
public static class Cat extends Animal {
    boolean likesCream;
    public int lives;
}

@Controller
public class MyController {

    //REST service
    @RequestMapping( value = "test")
    public  @ResponseBody String save(@RequestBody  Animal animal){
        System.out.println(animal.getClass());
        return success;
    }
}

发送到/test

{
    "type": "dog",
    "barkVolume": 23.3
}

将显示 Dog.class

发送到/test

{
    "type": "cat",
    "likesCream": true,
    "lives": 42
}

将显示 Cat.class

如何在 Swagger 中描述多态端点?

最佳答案

我遇到了和你一样的问题。不幸的是,swagger-ui 现在不支持它。 你可以在github上看到讨论。他们已经就此提出了几个问题。而 swagger 仍然无法提供该功能。确实有解决方法,github上有人提到过,也许你可以试试。

ringgelerch commented on Aug 10

This is a very important feature for us as well. We use a workaround at the moment:

For the GET method we define multiple responses like "200 Cat" and "200 Dog". For PUT and POST we use different paths like "path/to/animals/animal (Cat)". To use the "try out" feature of swagger ui we created a PUT and POST with the valid path "path/to/animals/animal". To send a request just copy the body content from the Cat PUT or POST to the generic one.

It would be greate to see the discriminator be supported very soon, because with upper workaround our api spec is hard to maintain and the rendered ui is not easy to read.

链接在这里
https://github.com/swagger-api/swagger-ui/issues/2438https://github.com/swagger-api/swagger-ui/issues/1526

关于java - 如何在 Swagger 中描述多态端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420181/

相关文章:

java - 如何获取 IProject 中的所有文件

java - 使用 shibboleth sso 进行授权

java - 使用jython从python访问java类

java - @RequestBody 对象不会自动反序列化

java - 插入带有子项的@OneToMany 关系对象而不在子表中插入父项ID?

Java jackson : Can I hold in a json the type to deserialize it to?

java - model.addAttribute ("name",值)和 mv.addObject ("name",值)之间的区别?

spring - 哪个 JAR 文件包含 JsonProcessingException 类?

java - 无法将 java.util.ArrayList 的实例反序列化出 VALUE_STRING

java - 自定义序列化程序,可回退到默认序列化