I am trying to parse json data from request body to JsonOject.
Spring Reactive get body JSONObject using ServerRequest
// it didn't work.
JSONObject bodyData = serverRequest.bodyToMono(JSONObject.class).toProcessor().peek();
I tried it as referenced in the link above, but it didn't work. I want to know why this is.
For the test, two router beans were created as shown below.
// router
@Bean
public RouterFunction<ServerResponse> routeJsonBodyPOST2(JsonObjectHandler jsonObjectHandler) {
return route(RequestPredicates.POST("/json/post2")
.and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)), jsonObjectHandler::getStringByJsonObject);
}
@Bean
public RouterFunction<ServerResponse> routeJsonBodyPOST3(JsonObjectHandler jsonObjectHandler) {
return route(RequestPredicates.POST("/json/post3")
.and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)), jsonObjectHandler::getJsonObject);
}
// handler
// I checked the json data in onNext. I understood this.
public Mono<ServerResponse> getStringByJsonObject(ServerRequest request) {
Mono<String> response = request.bodyToMono(JSONObject.class).log()
.map(jsonObject -> {
String name = (String) jsonObject.get("name");
System.out.println(name);
return name;
});
return ServerResponse.ok()
.body(response, String.class);
}
// Only onComplete is called and exits. I don't understand this.
public Mono<ServerResponse> getJsonObject(ServerRequest request) {
Mono<JSONObject> response = request.bodyToMono(JSONObject.class).log();
response.onErrorResume(error -> {
System.out.println(error);
return Mono.error(error);
}).subscribe(
jsonObject -> System.out.println("test : " + jsonObject),
error -> System.out.println(error.getMessage()),
() -> System.out.println("complete")
);
// Mono<JSONObject> jsonObjectMono = request.bodyToMono(JSONObject.class);
// jsonObjectMono.subscribe(System.out::println);
// JSONObject peek = jsonObjectMono.toProcessor().peek();
// System.out.println(peek);
// just for test.
return ServerResponse.ok().build();
}