Posting JSON to Spring MVC Controller

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);
  }
});

19 thoughts on “Posting JSON to Spring MVC Controller”

  1. 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.

    1. I’ve updated the tutorial to return a Java class which will be translated to JSON using

  2. 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.

    1. How are you posting the json data? The request header has to have contentType: ‘application/json’,

    1. 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

    2. 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.

    1. First create a Java object to map each member of the array, then map them into a List. Eg: List users

  3. 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

    Reply
    1. If the controller field allow null value it will be set as null, otherwise you’ll get an error response

  4. 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

    Reply
    1. Check the character encoding used to post and parse the text. IIRC there’s a HTTP header for it

Leave a Reply