在JSP中使用JsonArray的Ajax jquery

时间:2012-11-04 04:18:33

标签: jsp jquery arrays

我正在使用JSon-RPC library

的Servlet

我想将List<Student>放入与JSonArray相同的{["name":"AAA","age":"24"]["name":"BBB","age":"12"]}JsonArray有一个构造函数,它接受Collection与参数相同。 如果结果是JsonObject,那么我将使用方法out.print(instanceJsonObject.toString())回复客户端。 现在我不知道如何从服务器到客户端响应JsonArray

ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("Vu Duc Hoan", "C1010G", "24"));
list.add(new Student("Vu Duc Hoan2", "C1010G2", "242"));

JSONObject js = new JSONObject();
org.json.JSONArray array = new JSONArray(list);

客户端:

你能告诉我如何在JsonArray中获取数据吗?我正在使用$.getJson

btnJson.click(function(){
    $.getJSON("../DemoAjax/Controller?action=getJson",function(data){
});

1 个答案:

答案 0 :(得分:2)

我认为这是您正在寻找的servlet代码,但我认为您需要先将Student对象转换为JSONObject,然后将JSONObject放入{ {1}},此tutorial可能会对您有所帮助:

JSONArray

在javascript方法中,JSONObject js = new JSONObject(); org.json.JSONArray jsonArray = new JSONArray(list); // set the response content-type response.setContentType("application/json"); PrintWriter out = response.getwriter(); // writing the json-array to the output stream out.print(jsonArray); out.flush(); 中的data将包含此json数组,您可以使用此answer来获取html页面中的数据。