Reputation: 490
I am sending few 'fields' and 'lists' in JSON to Spring MVC Controller as below:
var data = {
'message' : 'Text data',
'**listOfIds**' : '350234983, 378350950',
'synchronizerToken' : formTokenId
};
$.ajax({
url : 'testURL.do',
type : 'post',
data : data,
cache : false,
dataType : 'json',
success : function (jsonResponse) {},
error : function (error) {}
});
In Spring MVC controller the URL handler looks like this:
@RequestMapping(value = "/testURL.do", method = RequestMethod.POST)
public ModelAndView executeTest( ListData listData) {
ModelAndView modelAndView = null;
JsonResponse jsonResponse = null;
modelAndView = executeTransaction(listData);
}
return modelAndView;
}
ListData.java
public class ListData{
private String message;
private List<String> **listOfIds** = new ArrayList<String>();
//getter/setters
The issue is listOfIds is not being returned as list. It is returned as single string '350234983, 378350950'
Can anyone suggest if anything is wrong here or is there any better way to receive list in JSON response?
Thanks, -Fonda
Upvotes: 5
Views: 47602
Reputation: 1613
1.)
Add gson jar
import com.google.gson.Gson;//import
Gson gson = new Gson();//create instance
gson.toJson(ListData);//convert it to json
2.)
Define below bean return jsonView from the controller.
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/>
Controller
import org.springframework.ui.ModelMap;
@RequestMapping(value = "/testURL.do", method = RequestMethod.POST)
public String executeTest(ModelMap model, ListData listData) {
ModelAndView modelAndView = null;
JsonResponse jsonResponse = null;
modelAndView = executeTransaction(listData);
model.addAttribute("paramName", modelAndView);
}
return "jsonView";
}
Change in ajax
$.ajax({
url : 'testURL.do',
type : 'post',
data : data,
cache : false,
dataType : 'json',
success : function (jsonResponse) {
var jsonValue = $.parseJSON(jsonResponse.paramName);
},
error : function (error) {}
});
viewsResolver config in mvc-servlet.xml
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/path/views.xml</value>
</property>
</bean>
Upvotes: 0
Reputation: 7898
Make listOfIds an array of strings instead of a single string.
'listOfIds' : ['350234983', '378350950'],
Upvotes: 7