【问题标题】:JSON response with arraylist带有 arraylist 的 JSON 响应
【发布时间】: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&lt;Countries&gt;) 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,它包含编码示例。检查出来。

标签: java ajax json


【解决方案1】:

这是您使用的 json-simple 库吗?如果是:

PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
js.put("countries", country); // make sure the Country class overrides toString()

// set the response content-type
response.setContentType("application/json");

// writing the json-array to the output stream
out.print(js.toJSONString());
out.flush();

您似乎正试图将一个匿名数组插入到您的 json 字符串中。你不能这样做,它不是有效的 JSON。例如,您的 JSON 不能看起来像:

{
    ["1st Country", "2nd Country", "3rd Country"]
}

...在 JSON 中至少需要一个键/值对,例如

{
    "countries": ["1st Country", "2nd Country", "3rd Country"]
}    

...所以“国家”是键,数组是值。如果您使用我上面给出的示例代码,那么您的服务器应该向浏览器返回一个 JSON 字符串,看起来像上面的有效 JSON 示例。因此,如果您的客户端 javascript 使用这样的 AJAX 调用(使用 jQuery)调用服务器:

$.ajax({
    type:     'GET',
    url:      '/your-server-path',
    dataType: 'json',
    success:  function(response, status, request) {
        // jQuery automatically converts the JSON object to a Javascript object 
        for (int i=0; i<response.countries.length; i++) {
            console.log("Country " + i + " is " + response.countries[i]);
        }
    }, 
    error: function(request, status, error) {
        console.log("Something went wrong...");
    }
});

另外,正如我在第一个代码sn-p中提到的,你必须重写你的Country类的toString()方法,这样每个Country实例都可以转换为字符串并添加到JSON数组中例如

@Override
public String toString() {
    // return some combination of variables in your Country class
    // or however you want a Country to be represented
}

【讨论】:

  • 客户端设置响应的方式,因为上面的方式实现得到错误错误(对象对象)
  • ArrayList country=new ArrayList(); country=FetchData.getAllCountries(); Gson gson = 新 Gson(); JsonElement element = gson.toJsonTree(country, new TypeToken>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray(); response.setContentType("应用程序/json"); response.getWriter().print(jsonArray);
【解决方案2】:

来自 json-simple 的 Wiki https://code.google.com/p/json-simple/wiki/EncodingExamples#Example_2-4_-_Encode_a_JSON_array_-_Using_List_and_streaming

LinkedList list = new LinkedList();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
StringWriter out = new StringWriter();
JSONValue.writeJSONString(list, out);
String jsonText = out.toString();
System.out.print(jsonText);

所以你的应该是

PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
JSONArray jsonArray = new JSONArray(country);

StringWriter out = new StringWriter();
JSONValue.writeJSONString(country, out);

// set the response content-type
response.setContentType("application/json");

// writing the json-array to the output stream
out.print(out.toString());
out.flush();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多