[英]Customising json output in spring hateoas
我正在構建基於 spring(spring boot)的 api。 是否可以從 hateoas 庫 json 輸出生成的 _embedded 關鍵字中刪除? 我希望我的項目集合不在 _embedded 下顯示。 我知道它違反了規范,但是我想知道是否有簡單的方法來自定義輸出但仍然使用 spring hatoas? 如果不可能,我是否應該使用不同的 api 構建庫,以便在生成的輸出方面具有更大的靈活性,在這種情況下,您有什么建議?
我的控制器代碼:
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
HttpEntity<Resources<Author>> getAllAuthors() {
Resources<Author> resources = new Resources<>(this.authorsService.findAll());
resources.add(this.entityLinks.linkToCollectionResources(Author.class));
return new ResponseEntity<>(resources, HttpStatus.OK)
這里還有一些已知問題: https : //github.com/spring-projects/spring-hateoas/issues/175
您需要編寫一個自定義序列化程序,它將 hateoas 對象 e 轉換為所需的對象。
請參閱分頁自定義響應的示例:
@Component
public class CustomPageResponseSerializer extends JsonSerializer<Page> {
@Autowired
private PagedResourcesAssembler<Page> pagedResourcesAssembler;
@Override
public void serialize(Page page, JsonGenerator gen, SerializerProvider provider) throws IOException {
PagedModel pageModel = pagedResourcesAssembler.toModel(page);
CustomPageResponse pageResponse = CustomPageResponse.builder()
.data(page.toList())
.page(PaginationDataResponse.builder()
.page(page.getNumber())
.pageSize(page.getSize())
.totalPages(page.getTotalPages())
.totalElements(Math.toIntExact(page.getTotalElements()))
.links(
PaginationLinksResponse.builder()
.first(getLink(pageModel.getLink(IanaLinkRelations.FIRST)))
.last(getLink(pageModel.getLink(IanaLinkRelations.LAST)))
.previous(getLink(pageModel.getPreviousLink()))
.next(getLink(pageModel.getNextLink()))
.build()
)
.build())
.build();
new PaginationObjectMapper().writeValue(gen, pageResponse);
}
private String getLink(Optional link) {
return link.isPresent() ? ((Link)link.get()).getHref() : "";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.