如何从 Spring Boot 控制器中的 Flux<String> 获取 JSON 格式?

How to get JSON format from a Flux<String> in SpringBoot Controller?

我正在学习 Reactor。我用project-reactor搭建了一个Reactor SpringBootDemo.I已经完成了很多功能并且在我的DEMO中成功GET/POST

现在我遇到一个问题,Controller 的结果return 不是JSON 格式而是一个像这样的连接字符串:"reactortestPostTitleReactorProgramming Reactor 3.xtestbypostman"。(我使用POSTMAN 来测试我的DEMO)

我想要的是这样的JSON格式:["reactortestPostTitle", "ReactorProgramming Reactor 3.x", "testbypostman"]

现在我把我的代码:
我的基本数据结构 BLOGPOST 在 Entity 包中定义,使用 .getTitle() 方法可以 return String 类型的博客标题 :

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BLOGPOST {
    @Id
    String id;
    String title;
    String author;
    String body;
}

View 中的模型,在此 class 中,我使用 @JsonCreator 并且有效:

@Value
@Builder
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
public class PostContent {
    @NonNull
    String title;
    @NonNull
    String author;
    @NonNull
    String body;
}

控制器代码,我遇到的问题是:

// Get All titles list of Blogs
@GetMapping(value = "/api/blog/alltitles", produces = MediaType.APPLICATION_JSON_VALUE)
public Flux<String> getPostAllTitles() {
    return service.getAllTitlesByFlux();
}

服务Class代码,我使用JPArepository.findAll()方法从Mysql调用数据: :

public Flux<String> getAllTitlesByFlux(){
    return Flux.fromIterable(repository.findAll())
               .map(post -> {return post.getTitle();});
}

那么,如何通过 Flux<String> getPostAllTitles()

获得 JSON 格式的字符串列表

看看这个。这就是你的情况。您可以在那里使用提供的解决方案。


简单的解决方案: 您只需将 Flux<String> 更改为 Flux<Object>

@GetMapping("/api/blog/alltitles")
public Flux<Object> getPostAllTitles() {
    return service.getAllTitlesByFlux();
}

另一个解决方案: 如果您不想采用上述两种方法,那么,您正在寻找 List<String> 并根据您的要求,您的 return 类型应该是 Mono<List<String>>。你可以看看这个collectList方法

// Get All titles list of Blogs
@GetMapping(value = "/api/blog/alltitles")
public Mono<List<String>> getPostAllTitles() {
    return service.getAllTitlesByFlux()
                  .take(3)
                  .collectList();
}