weixin_33743703 2014-05-06 08:39 采纳率: 0%
浏览 24

带有arraylist的JSON响应

I am new to JSON and jQuery and I want to get JSON data using AJAX. I want to show data using a submit button I try like this:

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

I get a compile time error: The constructor JSONArray(List<Countries>) is undefined. below way i try it working but i want to implemt using jason array

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

working below way

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);
  • 写回答

2条回答 默认 最新

  • DragonWar% 2014-05-06 08:52
    关注

    From the Wiki for 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);
    

    So yours would be

    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();
    
    评论

报告相同问题?