java jdbc如何将数据正确地添加到JsonObject中

java jdbc如何将数据正确地添加到JsonObject中,java,jdbc,jsonobject,Java,Jdbc,Jsonobject,我正在使用JDBC从MySQL数据库中检索2条记录,并将它们转换为JsonObject,但是代码工作不正常,例如:我得到了这个结果 {"locations":[{"city":"OrlandoOrlando","state":"WVFL"}]} 而不是 {"locations":[{"city":"Orlando","state":"WV"},{"city":"Orlando","state":"WV"}]} 我知道我是如何得到,但似乎可以找到如何纠正它,这是我的代码 String city

我正在使用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);
问题出在上面的城市+和州+字符串中,但是如果我这样做

while (rs.next()) {
   city= rs.getString("city");
   state= rs.getString("state");
 }
它修复了所有问题,但只返回1条记录,而不是2条记录,然后看起来像这样

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

任何建议都很好。

我已经用这种方式进行了更改,以从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);

在循环之前创建JSONArray并在循环中添加提取的值怎么样??JSONArray ja=新的JSONArray();虽然(rs.next()){city=rs.getString(“city”);state=rs.getString(“state”);jo.put(“city”,city);jo.put(“state”,state);ja.put(jo);}嘿,我刚试过,但结果只会给我{“locations”:[{“city”:“oralando”,“state”:“WV”}}}}结果。你的数据库中有FL的条目吗?你能检查3个不同州的记录吗?是的,我在记录的州栏下有一个FL,WV的条目,是的,我能。我正在尝试添加数据的新方法。嘿,非常感谢你的努力,非常感谢!!。看看这个线程,它的实现更加简洁:向下投票。如果我们在
rs
中返回了多行,这个解决方案不会导致
ja
只有一个
jo
值吗?感谢您的修订,这也会获得所有新记录。这只是复制了以前的答案并进行了一些调整。编辑现有的是更好的方法。
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);