2

我有一个使用 PagedResources 和 HAL 返回资源集合的 Spring Boot 应用程序。

这是一个常见响应的示例:

{
  "_embedded": {
    "mappings": [
      {
        "formId": "857353204373673",
        "formName": null,
        .....
      }
    ]
  },
  "_links": {.....},
  "page": {.....}
}

否则,如果要返回的集合为空(可能为空),则响应将是:

{
  "_links": {.....},
  "page": {.....}
}

我想要一个总是返回一个 JSON 的响应,其中包括 _embedded 节点及其所有字段(显然是空的),例如:

{
  "_embedded": {
    "mappings": []
  },
  "_links": {.....},
  "page": {.....}
}

我的选择是始终让客户看到我的 JSON 的整个结构(也许这不是最佳实践?)。

这是代码片段:

@RequestMapping(
        method = RequestMethod.GET,
        path = "/mappings")
@ResponseStatus(HttpStatus.OK)
@ApiImplicitParams({
        @ApiImplicitParam(name = "page", dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "size", dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "sort", dataType = "string",  paramType = "query", allowMultiple = true),
        @ApiImplicitParam(name = RestConfiguration.HEADER_ACCEPT_LANGUAGE, dataType = "string",  paramType = "header", defaultValue = RestConfiguration.DEFAULT_LOCALE_TAG)
})
public PagedResources<MappingResource> getMappings(@ApiParam(required = true) @PathVariable final Integer customerId,
                                                   @ApiIgnore @PageableDefault final Pageable pageable,
                                                   HttpServletRequest request) {

    ApplicationResourcesValidator.validateCustomerId(customerId);
    if (customerRepository.findOne(customerId) == null) {
        throw new CustomerNotFoundException(customerId);
    }

    customerIdProvider.set(customerId);

    Page<UserdbFormMapping> mappings = userdbFormMappingRepository.findAllIfUserdbValid(pageable);

    MappingResourceAssembler mappingResourceAssembler = new MappingResourceAssembler(
            MappingController.class,
            MappingResource.class,
            customerId,
            facebookApiClient,
            userdbRepository,
            userdbFormMappingRepository,
            userdbFormMappingFieldRepository,
            userdbFormSubscriptionLogCacheRepository,
            persistenceManager);

    LOGGER.info("serving " + request.getRequestURI());

    return mappingPagedResourceAssembler.toResource(mappings, mappingResourceAssembler);
}

任何建议表示赞赏!

在此先感谢,安德里亚。

4

0 回答 0