Sending a list in a JSON request

I am sending a few “fields” and “lists” to JSON in Spring MVC Controller, as shown 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, 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

Problem listOfIds is not returned as a list. It is returned as a single line '350234983, 378350950

Can anyone suggest if something is wrong, or is there a better way to get a list in a JSON response?

Thanks, -Fonda

+5
source share
2 answers

Make listOfIds an array of strings instead of a single string.

'listOfIds' : ['350234983', '378350950'],
+5
source

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 a bean below to 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";
}

Ajax change

$.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>
0
source

All Articles