How to pass JSON Object string or JSONArray string from javascript to spring controller

We usually send primitive data to spring controller by using @RequestParam annotation. But how to pass whole JSONObject string or JSONArray string to spring controller directly.

For that we have to include below jar files in buildpath

  1. jackson-core-asl-1.7.3.jar
  2. jackson-mapper-asl-1.7.3.jar

I have created Person pojo which will be mapped with javascript JSONObject exactly, Whatever the identifiers are there in this POJO should be there in Javascript JSON.

public class Person implements Serializable{
private String id;
private String firstName;
private String lastName;
//setters and getters
}

Pojo should implement Serializable interface, as  Jackson will serialize and deserialize to send data between server and client.

Our json data is :
{"persons": [
{
"firstName": "Ramesh",
"id": "id1",
"lastName": "Kotha"
},
{
"firstName": "Sathish",
"id": "id2",
"lastName": "Kotha"
}
]
}

Below is an ajax request from jsp.

$.ajax({
type: 'POST',
dataType: 'json',
contentType:'application/json',
url: "create_persons.htm",
data:JSON.stringify(arr),
success: function(data, textStatus ){
console.log(data);
//alert("success");
},
error: function(xhr, textStatus, errorThrown){
//alert('request failed'+errorThrown);
}
});

Now will see Spring controller Code:

@RequestMapping(value="/create_persons.htm")
public @ResponseBody createPerson(@RequestBody Person[] persons){
//here you can persons array as normal
for(Person person : persons){
System.out.println(person.getId());
}
}

By seeing @RequestBody annontation json data will be converted into Java Person[] and passed to persons array.

Add this in your Configuration file :

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>

That’s it, now if you pass json string to the spring controller, it will be converted into java POJO.

Responses

  1. Hi your tutorial was helpful in solving an issue I was having with my controller, thank you. However, I did find a few errors in your code blocks which slowed me down.

    There is an extra } after your ajax post. Also the configuration code block does not have a for the second bean and the <ref bean=“jacksonMessageConverter” /> portion is not correct. is what worked for me.

    Thanks.

  2. rameshcharykotha Avatar
    rameshcharykotha

    Thanks Nick, i have updated the code.

  3. Hi,
    Can you please post the complete jsp file ?
    thanks lot

  4. Hi to all, how is the whole thing, I think every one is getting
    more from this web site, and your views are good in support of new users.

  5. This is awesome, thank you! Before, I tried a different solution which involves an additional class that extends ArrayList because many comments on stackoverflow said this would be the only way to accomplish sth. like:

    createPerson(@RequestBody List persons){

    Didn’t think that the simple solution is to *not* use List interface, but a simple Array. For further processing, I create my desired list out of the array via

    Arrays.asList(persons);

  6. Is it possible to do the same thing, but to a map pair in the controller rather than the person[] model.
    Mainly because am sending generic data through the Ajax request.

  7. when you add “public @ResponseBody createPerson” , the netbeans doesnt find “@ResponseBody”. How do you add library for “@ResponseBody”? Can you help that please?

    1. rameshcharykotha Avatar
      rameshcharykotha

      @ResponseBody is an annotation which is there in Spring MVC. Please add Spring MVC libraries to your project

  8. Is this doable in Spring 4/Jackson 2?

    Ive tried using your code in a project but I get bad request errors. I suspect something has changed in Jackson but at a loss on how to fix it.

    Any help would be much appreciated!

  9. Can you provide how we write the client side code (jsp) to set values for Person object. I am getting Uncaught Error “HTTP Status 400 -“.

  10. can we do the thing without adding bean to configuration like using maven dependency

  11. thanks man you saved me you the best

  12. Tharaka Wijesooriya Avatar
    Tharaka Wijesooriya

    public @ResponseBody createPerson(@RequestBody Person[] persons) is wrong

  13. Thank youu for writing this

Leave a reply to Emre Tiryaki Cancel reply