【发布时间】:2014-11-03 12:13:48
【问题描述】:
在我的 Java Web 服务中尝试以 JSON 格式返回从 MySQL 获取的数据时遇到了一些问题:
public String getAllEvent() {
JSONArray jsonArray = new JSONArray();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/mydb", "root", "root");
PreparedStatement statement = con
.prepareStatement("SELECT * FROM event");
ResultSet result = statement.executeQuery();
while (result.next()) {
JSONObject eventInfo = new JSONObject();
eventInfo.put("eventID", result.getString("eventID"));
eventInfo.put("eventName", result.getString("eventName"));
eventInfo.put("eventDesc", result.getString("eventDesc"));
eventInfo.put("eventDate", result.getString("eventDate"));
eventInfo.put("eventTime", result.getString("eventTime"));
eventInfo.put("eventX", result.getString("eventX"));
eventInfo.put("eventY", result.getString("eventY"));
eventInfo.put("eventBy", result.getString("eventBy"));
jsonArray.put(eventInfo);
}
String jsonStr = jsonArray.toString();
return jsonStr;
}
catch (JSONException je) {
return null;
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
return jsonArray.toString();
}
有两个错误信息,一个在 jsonArray.put(eventInfo); 有错误信息:
The method put(JSONObject) is undefined for the type JSONArray
另一个是 JSONException:
JSONException cannot be resolved to a type
有什么想法吗?我必须将 json-simple-1.1.jar 作为外部库导入到我的项目中,否则 JSONObject 将收到未解析类型的错误消息。
提前致谢。
【问题讨论】:
-
抱歉,我该如何在我的代码中实现它?
-
你能给我提供 json 库的链接吗?因为我只设法在网上找到了 json-simple 库
-
在我看来这是
org.json库。
标签: java mysql json arrays jsonobject