Trying to use Spring Boot REST to Read JSON String from POST
I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761
But if you can't use a Java class you can use one of these two solutions.
Solution 1: you can do it receiving a Map<String, Object>
from your controller:
@RequestMapping( value = "/process", method = RequestMethod.POST)public void process(@RequestBody Map<String, Object> payload) throws Exception { System.out.println(payload);}
Using your request:
curl -H "Accept: application/json" -H "Content-type: application/json" \-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process
Solution 2: otherwise you can get the POST payload as a String
:
@RequestMapping( value = "/process", method = RequestMethod.POST, consumes = "text/plain")public void process(@RequestBody String payload) throws Exception { System.out.println(payload);}
Then parse the string as you want. Note that must be specified consumes = "text/plain"
on your controller.In this case you must change your request with Content-type: text/plain
:
curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \-d '{"name":"value"}' http://localhost:8080/myservice/process
To add on to Andrea's solution, if you are passing an array of JSONs for instance
[ {"name":"value"}, {"name":"value2"}]
Then you will need to set up the Spring Boot Controller like so:
@RequestMapping( value = "/process", method = RequestMethod.POST)public void process(@RequestBody Map<String, Object>[] payload) throws Exception { System.out.println(payload);}
To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode
. The appropriate converter is automatically configured.
@PostMapping(value="/process") public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) { System.out.println(payload); }