Bil*_*ill 10 java rest jersey swagger swagger-ui
我有一个WidgetDto,我用swagger UI注释进行了注释.最终的响应包WidgetDtos的列表,元数据层(每21页这个 REST风格的最佳实践文件).例如:
{
"data" : [
{
"id" : 1234,
"prop1" : "val1"
...
},
{
"id" : 5678,
"prop1" : "val2"
...
},
...
]
}
Run Code Online (Sandbox Code Playgroud)
我的java代码如下所示:
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Get all widgets.",
response = WidgetDto.class
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Returns the list of widgets.")
})
public Response getWidgets() {
List<WidgetDto> widgets;
...
Map<String, Object> responseBody = new HashMap<>();
responseBody.put("data", widgets);
return Response.ok(responseBody).build();
}
Run Code Online (Sandbox Code Playgroud)
我想在多个资源上重用这个模式,我不想为每个响应类型创建列表DTO.是否有一种优雅的方式来使用招摇来记录这些类型的响应主体?
您的元数据不是资源的一部分,而是资源表示的一部分。
在我的例子中,响应类型是“ application/hal+json ”和“application/json”,它们每个都使用具有不同元数据的不同包装器。为了解决这个问题,我创建了一个外部文档来解释这两个包装器以及它们中的每个包装器如何用元数据表示单个资源和资源列表。
我认为我的选择是正确的,因为我将其表示的资源分开(根据此RESTful 最佳实践文档的第 7 页“通过表示操作资源” )
在您的情况下,您返回 WidgetDtos 列表,元数据层是资源表示的一部分。
但是,您可以使用通用类,例如spring-hateoas使用的 Resource 和 Resources :
public class Resources<T> implements Iterable<T> {
private final Collection<T> content;
Resources(Iterable<T> content) {
this.content = new ArrayList<T>();
for (T element : content) {
this.content.add(element);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Get all widgets.",
response = WidgetDto.class
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Returns the list of widgets.")
})
public Response getWidgets() {
List<WidgetDto> widgets;
...
return Response.ok(new Resources<WidgetDto>(widgets)).build();
}
Run Code Online (Sandbox Code Playgroud)