我需要我的端点以以下 json 格式返回数据:
{
"code": "SUCCESS",
"message": "SUCCESS",
"errors": null,
"data": []
}
这是我的 Controller 代码:
@GetMapping(value = "/productSubcategories", produces = MediaType.APPLICATION_JSON_VALUE)
public Flux<MyDTO> getMyObjects() {
return myObjectService.getAll()
.map(myObject -> modelMapper.map(productSubcategory, MyObject.class));
}
将所有 MyDTO 对象包装在 json 响应的“数据”部分的最佳方法是什么?
最佳答案
我不确定您想要实现什么,但我认为您需要 collectList()
@GetMapping(value = "/productSubcategories", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity> getMyObjects() {
return myObjectService.getAll()
.map(myObject -> modelMapper.map(productSubcategory, MyObject.class)) // here your have Flux<MyObject>
.map(obj -> modelMapper.map(obj, MyDTO.class)) // lets assume that here is conversion from MyObject to MyDTO - Flux<MyDTO>
.collectList() // now you got Mono<List<MyDTO>>
.map(dtos -> ResponseEntity.status(HttpStatus.OK).body(dtos));
}
关于reactive-programming - 如何将 Flux<MyObject> 包装在 ResponseEntity 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743663/