【发布时间】:2014-05-06 08:39:00
【问题描述】:
我是 JSON 和 jQuery 的新手,我想使用 AJAX 获取 JSON 数据。我想使用提交按钮显示数据我尝试这样:
PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
JSONArray jsonArray = new JSONArray(country);
// set the response content-type
response.setContentType("application/json");
// writing the json-array to the output stream
out.print(jsonArray);
out.flush();
我收到编译时错误:The constructor JSONArray(List<Countries>) is undefined。
下面我尝试它的工作,但我想使用 jason 数组来实现
PrintWriter out = response.getWriter();
ArrayList<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
String json = new Gson().toJson(country);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.write(json);
在下面工作
ArrayList<Countries> country=new ArrayList<Countries>();
country=FetchData.getAllCountries();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
【问题讨论】:
-
这个错误意味着 JSONArray 不接受 List / 或者它的构造函数中只接受一个 List。
-
您使用的是哪个 JSON 库?
-
使用 jsaon 数组的数组列表响应是可能的或任何其他解决方案
-
使用的 json-simple-1.1.1.jar 库
-
看看我发现了什么! code.google.com/p/json-simple/wiki/EncodingExamples .... 它是那个 json 库的 Wiki,它包含编码示例。检查出来。