new to Spring WebFlux, trying to return array of strings in one endpoint and for some reason it returns one concatenated string istead of JSON array.
Wrapping it with some class solves the problem but wonder how to actually return array of strings? Returning for example Array<String>
works as expected
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")
}
The response of the service endpoint that returns an array of JSON objects, will look like this. We need a minimal setup for this application. First, is to add required maven/gradle dependency and the other is to create model classes to parse the JSON data into. In order to use the WebClient, we need to add a dependency on Spring WebFlux.
Reactive Libraries spring-webfluxdepends on reactor-coreand uses it internally to compose asynchronous logic and to provide Reactive Streams support. Generally, WebFlux APIs return Fluxor Mono(since those are used internally) and leniently accept any Reactive Streams Publisherimplementation as input.
With Fluxor Mono, you should never have to block in a Spring MVC or Spring WebFlux controller. Simply return the resulting reactive type from the controller method. The same principle apply to Kotlin Coroutines and Spring WebFlux, just use suspending function or return Flowin your controller method . 2.9. Testing
For creating an example using the Flux stream type with Spring Flux framework, you have to create a Spring Boot application. In my case I used Spring Initializr : You have to select as dependency "Reactive Web", generate the project and open it in your IDE tool. In my case, I used Spring Tool Suite. Your POM must look like this:
Got an answer from Sébastien Deleuze (Spring framework committer) in Twitter https://twitter.com/sdeleuze/status/956136517348610048
Indeed when element type is String, the handler method is expected to provide directly well formed JSON String chunks, no serialization with Jackson is involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With