【问题标题】:java jdbc how can I properly add data into JsonObjectjava jdbc如何正确地将数据添加到JsonObject中
【发布时间】:2015-07-01 01:58:40
【问题描述】:

我正在使用 JDBC 从 MySQL 数据库中检索 2 条记录并将它们转换为 JsonObject,但是代码无法正常工作,例如:我得到了这个结果

{"locations":[{"city":"OrlandoOrlando","state":"WVFL"}]}

而不是

{"locations":[{"city":"Orlando","state":"WV"},{"city":"Orlando","state":"WV"}]}

我知道我是怎么做到的,但似乎可以找出如何纠正它,这是我的代码

String city="";
String state="";
try {
   JSONObject jo = new JSONObject();
   Connection conn = DB.getConnection();
   ResultSet rs;
  PreparedStatement ps = conn.prepareStatement("select city,state from zips limit 2");
   rs = ps.executeQuery();
   while (rs.next()) {
// The problem is in this area the: city+ and state+
       city+= rs.getString("city");
       state+= rs.getString("state");
   }
   jo.put("city",city);
   jo.put("state", state);
   JSONArray ja = new JSONArray();
   ja.put(jo);
   JSONObject mainObj = new JSONObject();
   mainObj.put("locations", ja);

问题出在上面的 city+ 和 state+ 字符串中,但是如果我这样做

while (rs.next()) {
   city= rs.getString("city");
   state= rs.getString("state");
 }

它修复了所有问题,但只取回 1 条记录而不是 2 条记录,看起来像这样

{"locations":[{"city":"Orlando","state":"WV"}]}

任何建议都会很棒..

【问题讨论】:

  • 如何在循环之前创建 JSONArray 并在循环中添加提取的值? JSONArray ja = new JSONArray();while (rs.next()) { city= rs.getString("city"); state= rs.getString("state");jo.put("city",city); jo.put("state", state);ja.put(jo); }
  • 嘿,我刚试过,但结果只给了我 {"locations":[{"city":"Orlando","state":"WV"}]}。
  • 您的数据库中有 FL 条目吗?你能检查 3 条不同状态的记录吗?
  • 是的,我在我的记录中的状态列下有一个带有 FL,WV 的条目,是的,我可以。我正在尝试附加数据的新方法。

标签: java jdbc jsonobject


【解决方案1】:

我进行了更改,以便从 SQL 输出构建 JSONArray。

JSONObject jo = new JSONObject();
Connection conn = DB.getConnection();
ResultSet rs;
PreparedStatement ps = conn.prepareStatement("select city,state from zips limit 2");
rs = ps.executeQuery();
JSONArray ja = new JSONArray();
while (rs.next()) {
    jo.put("city", rs.getString("city"));
    jo.put("state", rs.getString("state"));
    ja.put(jo);
}

JSONObject mainObj = new JSONObject();
mainObj.put("locations", ja);

【讨论】:

  • 嘿,非常感谢,非常感谢!
  • 看看这个线程以获得更清晰的实现:stackoverflow.com/questions/17160351/…
  • 投反对票。如果我们在rs 中返回了多行,这个解决方案不会导致ja 只有一个jo 值吗?
【解决方案2】:
JSONObject jo = null;
Connection conn = DB.getConnection();
ResultSet rs;
PreparedStatement ps = conn.prepareStatement("select city,state from zips limit 2");
rs = ps.executeQuery();
JSONArray ja = new JSONArray();
while (rs.next()) {
    jo = new JSONObject();
    jo.put("city", rs.getString("city"));
    jo.put("state", rs.getString("state"));
    ja.put(jo);
}
JSONObject mainObj = new JSONObject();
mainObj.put("locations", ja);

【讨论】:

  • 感谢修改,这也获得了所有新记录。
  • 这只是复制以前的答案并稍作调整。编辑现有是更好的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多