I'm using Spring Boot (latest version, 1.3.6) and I want to create a REST endpoint which accepts a bunch of arguments and a JSON object. Something like:
curl -X POST http://localhost:8080/endpoint \ -d arg1=hello \ -d arg2=world \ -d json='{"name":"john", "lastNane":"doe"}'
In the Spring controller I'm currently doing:
public SomeResponseObject endpoint( @RequestParam(value="arg1", required=true) String arg1, @RequestParam(value="arg2", required=true) String arg2, @RequestParam(value="json", required=true) Person person) { ... }
The json
argument doesn't get serialized into a Person object. I get a
400 error: the parameter json is not present.
Obviously, I can make the json
argument as String and parse the payload inside the controller method, but that kind of defies the point of using Spring MVC.
It all works if I use @RequestBody
, but then I loose the possibility to POST separate arguments outside the JSON body.
Is there a way in Spring MVC to "mix" normal POST arguments and JSON objects?
Send JSON Data in POST Spring provides a straightforward way to send JSON data via POST requests. The built-in @RequestBody annotation can automatically deserialize the JSON data encapsulated in the request body into a particular model object. In general, we don't have to parse the request body ourselves.
Create RESTEasy Web Service to Produce JSON with @BadgerFish Now create a class whose methods will be exposed to the world as web service. Use JBoss @BadgerFish annotation that supports to return response as JSON. To return JSON as response we need to use media type as application/json.
Yes,is possible to send both params and body with a post method: Example server side:
@RequestMapping(value ="test", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) @ResponseBody public Person updatePerson(@RequestParam("arg1") String arg1, @RequestParam("arg2") String arg2, @RequestBody Person input) throws IOException { System.out.println(arg1); System.out.println(arg2); input.setName("NewName"); return input; }
and on your client:
curl -H "Content-Type:application/json; charset=utf-8" -X POST 'http://localhost:8080/smartface/api/email/test?arg1=ffdfa&arg2=test2' -d '{"name":"me","lastName":"me last"}'
Enjoy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With