0

I want to pass two List<String> to Gson and catch them with $.post in my jQuery. Currently I have my first list in my servlet:

String json_list = gson.toJson(suggested_list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json_list);

and I get it with the $.post like this:

$(document).ready(function() {
    $(".word_sugest").click(function() {
    var physical_exam =  jQuery("textarea#examination").val();
        $.post("MyServlet", { examination : physical_exam},function(responseJson) {
        var $textarea = $('<textarea rows="10" cols="20" id="words_suggested">').appendTo($('#words'));
        var areavalue = $('#words_suggested').val();    
            $.each(responseJson, function(key,value) {
            $('#words_suggested').val($('#words_suggested').val()+value+"\n");
            });
        });
    });
});

How can I get another list with the same $.post Ajax-event? Can someone please help?

4

2 回答 2

1

我认为最简单的解决方案是让您的 AJAX 调用返回 JSON 对象而不是列表。这样你就可以命名你的列表。以下是输出外观的示例:

{
  list1: ["A", "B", "C", "D"],
  list2: ["R", "S", "T", "U", "V", "W"]
}

这是通过创建这样的 Java 对象来完成的:

public class CustomObjResponse {
  private List<String> list1;
  private List<String> list2;
  // Getters/setters
}

然后,当您使用两个列表填充对象时,您的 Gson 调用将如下所示:

String json_obj = gson.toJson(customObjResp);
于 2013-04-03T16:33:57.553 回答
0

其中一种方法是返回列表对象的列表并相应地用 JavaScript 解析它们:

List<List<String>> suggestedList = new ArrayList<List<String>>();
suggestedList.add(new ArrayList<String>);
suggestedList.add(new ArrayList<String>);
String jsonList = gson.toJson(suggestedList);
于 2013-04-03T16:34:52.963 回答