Home > Java, Spring > How to pass JSON Object string or JSONArray string from javascript to spring controller

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.

About these ads
Categories: Java, Spring
  1. Nick
    April 17, 2013 at 9:37 pm

    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
    April 17, 2013 at 9:41 pm

    Thanks Nick, i have updated the code.

  3. June 19, 2013 at 11:11 pm

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

  4. July 24, 2013 at 12:42 pm

    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. JS
    February 7, 2014 at 9:54 pm

    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. AJemei
    June 25, 2014 at 5:44 pm

    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. Emre Tiryaki
    July 29, 2014 at 2:27 pm

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

    • rameshcharykotha
      August 3, 2014 at 2:21 am

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

  8. Steve
    August 29, 2014 at 8:32 pm

    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!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: