我有一个WidgetDto,它已经用醒目的UI注释进行了注释。最终响应将在WidgetDtos列表中包装一层元数据(按this RESTful最佳实践文档的第21页)。例如:

{
  "data" : [
    {
      "id" : 1234,
      "prop1" : "val1"
      ...
    },
    {
      "id" : 5678,
      "prop1" : "val2"
      ...
    },
    ...
  ]
}

我的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();
}

我想在多种资源上重用此模式,并且我不想为每种响应类型创建列表DTO。是否有一种优雅的方法来使用招摇来记录这些类型的响应主体?

最佳答案

元数据不是资源的一部分,而是资源表示的一部分。

在我的情况下,响应类型为'application/hal+json''application / json',它们每个都使用具有不同元数据的不同包装器。
为了解决这个问题,我创建了一个extern文档来解释这两个包装器,并为每个包装器说明如何用元数据表示单个资源和资源列表。

我认为我的选择是正确的,因为我将其表示形式的资源分开了(每页第七页RESTful最佳实践文档的“通过表示形式对资源的操纵”)

对于您的情况,您将返回WidgetDtos列表,元数据层是资源表示形式的一部分。

但是,您可以使用通用类,例如this使用的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);
        }
    }
}

并像这样使用它:
@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();
}

07-24 09:45
查看更多