【问题标题】:Storing JsonObject into JsonArray & JsonException error message将 JsonObject 存储到 JsonArray & JsonException 错误消息中
【发布时间】: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 将收到未解析类型的错误消息。

提前致谢。

【问题讨论】:

标签: java mysql json arrays jsonobject


【解决方案1】:

您导入了错误的库。您正在为 org.json 库编写代码,而不是 json-simple。

上面的链接会将您带到 Maven 存储库,如果您使用 Maven,您可以从该存储库导入到您的项目中,或者如果没有,则只需下载 jar。

【讨论】:

  • 但是您知道为什么上述方法会导致我的网络服务出现故障吗?
  • @IWasSoLost 我看不出任何明显的错误。我认为您需要将其作为一个单独的问题发布,并提供更多详细信息。
  • 你能帮我看看这个帖子吗:stackoverflow.com/questions/26715533/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多