[英]How to modify results from a Flux with Spring Reactive
I'm trying to convert the result of a Flux
to confirm with Json API spec. 我正在尝试转换Flux
的结果以通过Json API规范进行确认。 I have my standard method which converts the POJO
into the correct format and returns the json as a string. 我有我的标准方法,可以将POJO
转换为正确的格式,并以字符串形式返回json。 This works perfectly with a Mono
. 这与Mono
完美配合。
However I can't workout how to handle that with the Flux
. 但是我无法锻炼如何用Flux
处理。
@GetMapping(value = "/", produces = "application/vnd.api+json")
@ResponseBody
public Flux<String> findAll() {
return feedItemRepository.findAll().flatMap(this::createJsonApiSpec);
}
private Mono<String> createJsonApiSpec(FeedItem item) {
ObjectMapper objectMapper = new ObjectMapper();
ResourceConverter resourceConverter = new ResourceConverter(objectMapper, FeedItem.class);
JSONAPIDocument<Object> document = new JSONAPIDocument<>(item);
byte[] bytes = new byte[0];
try {
bytes = resourceConverter.writeDocument(document);
} catch (DocumentSerializationException e) {
e.printStackTrace();
}
return Mono.justOrEmpty(new String(bytes));
}
The find all gets all the FeedItem
s from a reactive mongo database. find all从反应式mongo数据库获取所有FeedItem
。 Then I get confused. 然后我很困惑。 Using flatMap
I can process each item at a time and convert it to a String (that confirms to the spec using the method below) but this doesn't work because each item is processed independently meaning invalid Json is returned (No ,
between each item). 使用flatMap
我可以一次处理每个项目并将其转换为String(使用以下方法确认符合规范),但这不起作用,因为每个项目都是独立处理的,这意味着返回了无效的Json(否,
每个项目之间)。
Is there another way to modify outgoing data from a Spring controller? 还有另一种方法来修改来自Spring控制器的传出数据吗?
Edit: I know I can make this work using 编辑:我知道我可以使用
public Mono<String> findAll() {
List<FeedItem> feedItems = feedItemRepository.findAll().collectList().block();
return writeList(feedItems);
}
But I'm sure that's a terrible idea to be using block()
like that. 但是我敢肯定,像这样使用block()
是一个糟糕的主意。
What does returning Mono<FeedItem>
give you? 返回Mono<FeedItem>
给您什么? Just a pointer: If FeedItem is a json pojo, you should be able to just return that. 只是一个指针:如果FeedItem是json pojo,则应该能够返回它。 No need to do the json marshalling/unmarshalling programmatically, the framework will do that for you. 无需以编程方式进行json编组/解组,该框架将为您完成。
Like here: https://dzone.com/articles/spring-webflux-first-steps and many other examples along the lines. 就像这里: https : //dzone.com/articles/spring-webflux-first-steps和许多其他示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.