从Spring WebFlux返回Flux <String>会返回一个字符串而不是JSON中的字符串数组

Art*_*lin 5 kotlin spring-boot spring-webflux

Spring WebFlux的新手,试图在一个端点返回字符串数组,并且由于某种原因它返回一个连接字符串而不是JSON数组.

用一些类包装它可以解决问题,但想知道如何实际返回字符串数组?例如,返回Array<String>按预期工作

class Wrapper(val data: String) {

@RestController
class Test() {
     @RequestMapping("/wrapped") // Returns valid JSON array: [{"value":"Hello"},{"value":"World"}]
     fun b() = Flux.just(Wrapper("Hello"),Wrapper("World"))
     @RequestMapping("/raw") // Returns not valid JSON with just one concatenated string: HelloWorld
     fun a() = Flux.just("Hello", "World")
}
Run Code Online (Sandbox Code Playgroud)

Art*_*lin 6

在Twitter上获得了SébastienDeleuze(Spring框架提交者)的答案https://twitter.com/sdeleuze/status/956136517348610048

实际上,当元素类型是String时,处理程序方法应该提供直接格式良好的JSON字符串块,不涉及与Jackson的序列化.

  • 答案很明确:你必须包装它。上面的答案有效;虽然你也可以这样做:`fun a() = Flux.just("Hello", "World").collectList()` (2认同)
  • 转换为列表会失去激活能力 (2认同)
  • 确实答案是正确的。文档中也对此进行了介绍 https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-codecs-jackson (2认同)