Vicky Vicky - 5 months ago 27
jQuery Question

Unable to bind json string to object in controller in Spring MVC?

I am trying to create a Spring MVC application and sending Ajax call on click of a submit Button.

Below is the Controller Method:

@ResponseBody
@RequestMapping(value = "/addTask" , method=RequestMethod.POST)
public String addTask(@ModelAttribute(value="task") Task task, BindingResult result, Model model){
String returnText = null;
System.out.println(task.getDescription()); // printing null
return "success" ;
}


But I am getting all the attributes in
Task
object as null .

However I am able to receive json as String in the controller and convert to Object via Gson api.

@ResponseBody
@RequestMapping(value = "/addTask" , method=RequestMethod.POST)
public String addTask(@RequestBody String task){
String returnText = null;

Gson gson = new Gson();
Task rr = gson.fromJson(task, Task.class);
taskList.add(rr);
return "success" ;
}


Below is the ajax code:

function doAjaxPost() {

var id = $('#id').val();
var desc = $('#description').val();
var dueDate = $('#dueDate').val();
var obj = { "id" : id, "description" : desc, "dueDate": dueDate};
console.log(obj)

$.ajax({
type : "POST",
contentType : "application/json",
url : "/spring/addTask",
data : JSON.stringify(obj),
dataType : 'json',
timeout : 100000,

success: function(response){
$('#description').val('');
$('#dueDate').val('');
$('#id').val('');
},
error: function(e){
alert('Error: ' + e);
console.log(e);
}
});
}


I have already added the below 2 dependency in pom.xml.

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.3</version>
</dependency>

Answer

The reason why JSON was not able to Bind to the object as I was not implement Serializable in my POJPO class.

After I implemented Serializable, the problem is solved. Thanks.