2017-07-31 87 views
0

我們使用Spring + Jackson(Java)。在我們的API中,我們可以發送不同的對象到同一個端點。 例如如何描述Swagger中的多態端點?

@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; 
    } 
} 

發送到/測試

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

將顯示Dog.class

發送到/測試

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

將顯示Cat.class

如何描述Swagger中的多態端點?

回答

0

我有和你一樣的問題。不幸的是,swagger-ui現在不支持這一點。 你可以在github上看到討論。他們已經就此開了幾個問題。雖然招搖仍然無法提供該功能。它的確有一個解決方法,有人在github上提到過,也許你可以試試看。

ringgelerch評論08月10日

這對我們來說是一個非常重要的功能,以及。我們現在使用一種解決方法:

對於GET方法,我們定義了多個響應,如「200 Cat」和「200 Dog」。 對於PUT和POST,我們使用不同的路徑,如「路徑/到/動物/動物(貓)」。要使用swagger ui的「試用」功能,我們使用有效路徑「path/to/animals/animal」創建了PUT和POST。要發送請求,只需將主體內容從Cat PUT或POST複製到通用的內容。

很快就會看到鑑別器的支持,因爲上面的解決方法我們的api規格很難維護,並且呈現的ui不容易閱讀。

的鏈接在這裏
https://github.com/swagger-api/swagger-ui/issues/2438https://github.com/swagger-api/swagger-ui/issues/1526