reactive-programming - 如何将 Flux<MyObject> 包装在 ResponseEntity 中

标签 reactive-programming spring-webflux project-reactor

我需要我的端点以以下 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/

相关文章:

java - 使用 rxjava 从实现可观察外部调用方法的自定义类发送事件

android - RxAndroid 中如何观察网络变化

scala - 如何使用 sttp 将响应读取为 Observable[String]

spring - 响应式(Reactive) WebClient 不发出响应

java - RabbitMQ + Reactor,传递消息后发送ACK?

java - 如何更新数组内文档的一部分? (MongoDB Spring Boot 响应式(Reactive))

java - Webflux WebClient java.lang.NullPointerException

spring-boot - 结合非阻塞和阻塞调用并在 Spring Webflux 中返回结果

spring - 使用 Spring WebFlux 客户端使用 REST 端点时出错

reactive-programming - 如何从 Mono SpringWebFlux 返回一个对象