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

java jdbc how can I properly add data into JsonObject

我正在使用 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"}]}

任何建议都很好..

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