如何在 Spring 中为 JSON API 建模自定义请求参数?

How to model custom request params in Spring for JSON API?

我目前正在尝试对 JSON API and work it into my Spring Boot project. I'm going to focus on filters 的查询参数结构、排序、分页以及可能的字段限制进行建模。

我想先从过滤开始,所以我希望我的 REST 端点能够处理 JSON-API 风格的 URL 请求,例如

GET /comments?filter[post]=1 HTTP/1.1

GET /comments?filter[post]=1,2 HTTP/1.1

GET /comments?filter[post]=1,2&filter[author]=12 HTTP/1.1

我的计划是在顶级 JsonApiParams 对象中捕获所有 JSON API 特定查询参数,例如:

public class JsonApiParams {
  private Filters filters;
  private Sorting sorting;
  private Paging paging;

  // getters, setters
}

然后建模出FiltersSortingPaging。然后这个 JsonApiParams 对象将被接受为我的 @RestController 端点中的请求参数,如下所示:

@RequestMapping(value = {"/api/v1/{entity}"},
            method = RequestMethod.GET,
            produces = {"application/vnd.api+json"})
@ResponseBody
public JsonApiTopLevel jsonApiGetByEntity(@PathVariable String entity, JsonApiParams params) {
  // convert params to DB query
}

那么,我应该如何为我的 JsonApiParams 对象建模才能处理上述请求(例如 /comments?filter[post]=1,2&filter[author]=12)?

幸运的是,Spring 开箱即用地使用地图的括号表示法。我能够使用以下模型像这样 /comments?filter[post]=1,2&filter[author]=12 格式化我的 URL 查询参数:

public class JsonApiParams {
    private Map<String, List<String>> filter;
    private List<String> sort;
    private Map<JsonApiPaginationKeys, Integer> page;

    // getters & setters
}

然后,就我而言,我将过滤器转换为 QueryDSL Predicate,并将 sortpage 字段转换为 Spring Pageable请求。轻松转换并无缝工作。