Java 如何将字符串数组添加到JSON
我目前正在一个servlet中编写一些代码,该servlet从数据库获取数据并将其返回给客户机。我遇到的问题是插入我收集的日期数组,并将它们添加到我将返回到客户端的JSON对象中 这是我正在尝试的代码,但它不断给出错误Java 如何将字符串数组添加到JSON,java,arrays,json,arraylist,Java,Arrays,Json,Arraylist,我目前正在一个servlet中编写一些代码,该servlet从数据库获取数据并将其返回给客户机。我遇到的问题是插入我收集的日期数组,并将它们添加到我将返回到客户端的JSON对象中 这是我正在尝试的代码,但它不断给出错误 dates = ClassdatesDAO.getdate(dates); ArrayList<String> ClassDates = new ArrayList<String>(); ClassDates = dates.getClassdates()
dates = ClassdatesDAO.getdate(dates);
ArrayList<String> ClassDates = new ArrayList<String>();
ClassDates = dates.getClassdates();
response.setContentType("application/json");
JSONObject Dates = new JSONObject();
Dates.put("dates", new JSONArray(ClassDates));
dates=ClassdatesDAO.getdate(日期);
ArrayList ClassDates=新的ArrayList();
ClassDates=dates.getClassdates();
setContentType(“应用程序/json”);
JSONObject日期=新JSONObject();
Dates.put(“Dates”,新的JSONArray(ClassDates));
在我的IDE中,我通过JSONArray中的ClassDates
得到了这个错误
构造函数JSONArray(ArrayList)未定义
您正在传递的是
ArrayList
实例,而不是Array
。因此,将列表转换为数组,然后将其作为参数传递,如下所示
Dates.put("dates", new JSONArray(ClassDates.toArray(new String[ClassDates.size()])));
注意:
json
API有一个接受java.util.Collection
的方法签名。因此,您正在使用其他库或旧版本您的JSONArray
来自哪个库?另外,将前两行替换为List classDates=dates.getClassdates()代码>。如果您在下一行重新分配引用,那么创建实例就没有意义了new JSONArray
应该可以工作,如果它是org.json版本的话。它有一个java.util.Collection的构造函数,ArrayList是Collection.BTW,java中的变量名应该以小写字母开头。类应以大写字母开头。
JSONObject Dates = new JSONObject();
JSONArray datesJSONArray = new JSONArray();
for (String date : ClassDates)
datesJSONArray.put(date);
try {
Dates.put("dates", datesJSONArray);
} catch (JSONException e) {
e.printStackTrace();
}