Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Flux<String> from Spring WebFlux returns one string instead of array of strings in JSON

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")
}
like image 897
Artem Yarulin Avatar asked Jan 24 '18 11:01

Artem Yarulin


People also ask

How to parse JSON data in spring webflux?

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.

Does spring-webflux support Reactive Streams?

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.

How to use fluxor mono with Spring MVC and webflux?

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

How to create an example using flux stream type with spring flux?

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:


Video Answer


1 Answers

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.

like image 62
Artem Yarulin Avatar answered Oct 20 '22 07:10

Artem Yarulin