Is it possible to use the annotation @RequestParam
to parse json formatted data from a request just like it is possible to parse application/x-www-form-urlencoded
encoded data?
I.e. if my request body is:
{ firstName : "John", lastName : "Doe" }
I would like to be able to have a method looking like
public void savePerson(@RequestParam String firstName, @RequestParam lastName) {
// handle data
}
Where the value of firstName
is "John" and the value of lastName
is "Doe". I have tried to make this work but it only works for application/x-www-form-urlencoded
encoded data. When sending json formatted data I get a 400
response saying that the paramaters are missing.
I am using Spring 3.2.0 and the Content-Type
header of my requests have been matching the data format.
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.
Spring uses Jackson internally for serializing and deserializing data in json format. It just works in most cases. Still, some corner cases can turn up where Spring cannot apply Jackson's default operations.
No. Change to this
public void savePerson(@RequestBody Person) {
and this
{"person" : { "firstName" : "John", "lastName" : "Doe" }
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