Spring MVC can be setup to automatically bind incoming JSON string into a Java object. Firstly, ensure you have jackson-mapper-asl included on the classpath:
org.codehaus.jackson jackson-mapper-asl 1.9.13
Assuming the JSON string we want to bind represent a person object like this:
{ name: "Gerry", age: 20, city: "Sydney" }
Which will be bound into following Java class:
public class Person { private String name; private int age; private String city; // getters & setters ... }
Declare the Spring MVC controller handler method like below. The handler method is mapped into path “addPerson” with method POST.
(value = "/addPerson", method = RequestMethod.POST, headers = {"Content-type=application/json"}) public JsonResponse addPerson( Person person) { logger.debug(person.toString()); return new JsonResponse("OK",""); }
Also pay attention to and the returned JsonResponse object. Here JsonResponse is a class to return the result of the addPerson operation.
public class JsonResponse { private String status = ""; private String errorMessage = ""; public JsonResponse(String status, String errorMessage) { this.status = status; this.errorMessage = errorMessage; } }
When converted to JSON this will look like this:
{ status : "OK", errorMessage : "" }
Below is an example jQuery based javascript handler that posts into the above Spring MVC handler and observe the returned value:
$.ajax({ type: "POST", url: "addPerson", data: JSON.stringify({ name: "Gerry", age: 20, city: "Sydney" }), contentType: 'application/json', success: function(data) { if(data.status == 'OK') alert('Person has been added'); else alert('Failed adding person: ' + data.status + ', ' + data.errorMessage); } });
Reblogged this on NU coder – latest developer technologies.
Reblogged this on .
It was very helpful, Thank You!!!
As I am new in spring and json. I am facing some parsing issue.
I set $ajax method on sumbit. It goes to controller , printing person data.
but as you redirecting to person (return “person”) It doesnt actually get redirected in my case.
Its coming to same client page in $ajax Call giving error. “Parser Error”.
What should I do?
I ll appreciate if you will provide complete example.
I’ve updated the tutorial to return a Java class which will be translated to JSON using
while trying this example, while submitting a POST i am getting 400 Bad request error.But if i use instead of the POST is succesful but with null values. Can you help me why there is 400 error.
How are you posting the json data? The request header has to have contentType: ‘application/json’,
Do you think it should work if I use instead of ?
I’ve been trying it for several days.
You can use both but they serve different purpose. is only suitable if you’re mapping a simple string values over form data while with you can pass complex JSON object
Yeap, that’s what I was afraid of, I can pas a complex JSON object bu I always need to map it to a JSON Object on the server, and I was trying to map it directly to a class with the similar structure, looks like it won’t work with , so my solution was to receive the JSONObject and do my own conversion on the server side.
You can still map into java object without though. Just pass your class name as parameter in the handler method and Spring will try to map it using java beans convention. See: http://docs.spring.io/spring/docs/4.0.5.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-arguments
what will be solution for sending json array to spring controller ?
First create a Java object to map each member of the array, then map them into a List. Eg: List users
what if i do not put “city” field in JSON.stringify while posting.? can i post json object with less field then controller’s parameter
If the controller field allow null value it will be set as null, otherwise you’ll get an error response
Thanks for this post. Could you please post an example of passing an array of person objects to spring controller ?
I have a problem with spanish characters, for example: á ñ, ó, etc. I did some test with charset utf8, but i can´t find any solution for it, apprecciate a help about it. Thanks a lot
Check the character encoding used to post and parse the text. IIRC there’s a HTTP header for it