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
- jackson-core-asl-1.7.3.jar
- 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.
Leave a reply to Emre Tiryaki Cancel reply