创建JSON数据

时间:2013-12-06 18:58:38

标签: java ajax json jsp

我使用this answer作为基础,但我无法让它发挥作用。我的主要问题是.add()方法在JSONArray类中不可用。

establishList只是一个ArrayList。

    JSONObject json      = new JSONObject();
    JSONArray  addresses = new JSONArray();
    JSONObject address;
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        for (Establishment est : establishmentList) {
            address = new JSONObject();
            try {
                address.put("name", est.getBusinessName());
                address.put("address", est.getAddress());
                address.put("rating", est.getRating());
                addresses.add(address); //<-- method not available, compiler error
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        json.put("Addresses", addresses);
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        out.println(json.toString());
    }   

我对JSON的导入是:

      import com.google.appengine.labs.repackaged.org.json.JSONArray;
      import com.google.appengine.labs.repackaged.org.json.JSONException;
      import com.google.appengine.labs.repackaged.org.json.JSONObject;

1 个答案:

答案 0 :(得分:1)

应该是:

            addresses.put(address);