Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access plain json body in Spring rest controller?

Having the following code:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) @ResponseBody public String greetingJson(@RequestBody String json) {     System.out.println("json = " + json); // TODO json is null... how to retrieve plain json body?     return "Hello World!"; } 

The String json argument is always null despite json being sent in the body.

Note that I don't want automatic type conversion, I just want the plain json result.

This for example works:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) @ResponseBody public String greetingJson(@RequestBody User user) {     return String.format("Hello %s!", user); } 

Probably I can use the use the ServletRequest or InputStream as argument to retrieve the actual body, but I wonder if there is an easier way?

like image 334
Marcel Overdijk Avatar asked Jul 25 '13 19:07

Marcel Overdijk


People also ask

How do I get raw JSON data from REST API?

To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.

Is @RequestBody required with @RestController?

If you don't add @RequestBody it will insert null values (should use), no need to use @ResponseBody since it's part of @RestController.

How do you read a body request in Spring boot?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.


1 Answers

Best way I found until now is:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) @ResponseBody public String greetingJson(HttpEntity<String> httpEntity) {     String json = httpEntity.getBody();     // json contains the plain json string 

Let me know if there are other alternatives.

like image 133
Marcel Overdijk Avatar answered Oct 06 '22 03:10

Marcel Overdijk