【问题标题】:How to get JSON format from a Flux<String> in SpringBoot Controller?如何从 Spring Boot Controller 中的 Flux<String> 获取 JSON 格式?
【发布时间】:2020-07-29 08:52:54
【问题描述】:

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

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

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

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

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

View 中的模型,在这个类中,我使用 @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();
}

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

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

那么,我如何通过Flux&lt;String&gt; getPostAllTitles()获得JSON格式的字符串列表

【问题讨论】:

    标签: json spring-boot project-reactor restful-url


    【解决方案1】:

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


    简单的解决方案:您只需将Flux&lt;String&gt; 更改为Flux&lt;Object&gt;

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

    另一种解决方案:如果您不想采用上述两种方法,那么,您正在寻找List&lt;String&gt;,根据您的要求,您的返回类型应为Mono&lt;List&lt;String&gt;&gt;。你可以看看这个collectList方法。

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

    【讨论】:

    • 感谢您的链接。你的链接对我帮助很大。还有更多,我尝试了你的 2 解决方案。第一个解决方案不起作用,也许通量不支持它;第二个不是反应堆风格,但有效。最后,我的成功解决方案是使用Flux&lt;char[]&gt;,Spring Boot 不会识别为原始 JSON 字符串。链接在这里[1]。 [1]stackoverflow.com/questions/44317740/…
    • 您的意思是Flux&lt;Object&gt; 不起作用?我在回答之前做了测试。
    猜你喜欢
    • 2011-05-30
    • 2023-03-15
    • 2018-01-13
    • 1970-01-01
    • 2018-09-06
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多