繁体   English   中英

带有arraylist的JSON响应

[英]JSON response with arraylist

我是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 下面的方式我尝试它工作,但我想使用杰森数组实现

           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);

您使用的是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...");
    }
});

另外,正如我在第一个代码段中提到的那样,您必须重写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
}

从Wiki中获取json-simple 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM