2
@GetMapping(produces = {
        MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_NDJSON_VALUE
})
public Flux<Some> read() {
}

When I curl with --header 'Accept: application/x-ndjson'

The outer array is gone but all new lines in each elements is not gone.

{
  "some": "thing"
}
{
  "some": "other"
}

How can I make them as single-line as possible?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

1

Assuming you are using webflux and by your example you are.

    @CrossOrigin // to be able to test it
    @RestController
    public class Controller {

        @GetMapping(value = "/json/flux", produces = MediaType.APPLICATION_NDJSON_VALUE)
        public Flux<Student> streamJsonObjects() {
            return Flux.interval(Duration.ofSeconds(1))
                    .take(10)
                    .map(i -> new Student("Name" + i, i.intValue()));
        }
    }

The DTO assuming you are using Project Lombok.

@Data
@AllArgsConstructor
public class Student {
    String name;
    int id;
}

Now how do you test it?

The best option I found was is Intellij http client GET http://localhost:8080/json/flux

Other option is to press f12 in to open the web console and paste this in

const decoder = new TextDecoder('utf-8');
const response = await fetch("http://localhost:8080/json/flux");
const reader = response.body.getReader();

while (true) {
    const {value, done} = await reader.read();
    if (done) break;
    const string = decoder.decode(value);
    console.log('Received', string);
}

console.log('Response fully received');