如何将列表对象放到JSon对象

时间:2014-08-21 11:58:52

标签: java json servlets arraylist resultset

在servlet中我试图在json对象中放一个列表,但我无法找到错误。我从ajax调用调用servlet,这是servlet代码,

Latlng latlng=new Latlng();
List<Latlng> vehicleList = new ArrayList<Latlng>();

sql ="SELECT a.vehicleno,a.lat,a.lng,a.status,a.rdate,a.rtime from latlng a,vehicle_details b where a.vehicleno=b.vehicleno and b.clientid="+clientid +"  and b.groupid in(select groupid from group_details where groupname='"+gname+"' and clientid='"+clientid+"')";
              resultSet = statement.executeQuery(sql);
              while(resultSet.next()){
                  String s=resultSet.getString("vehicleno");
                  latlng.setVehicleno(resultSet.getString("vehicleno"));
                  latlng.setLat(resultSet.getString("lat"));
                  latlng.setLat(resultSet.getString("lng"));
                  latlng.setLat(resultSet.getString("status"));
                  latlng.setLat(resultSet.getString("rdate"));
                  latlng.setLat(resultSet.getString("rtime"));
                  vehicleList.add(latlng);
                  System.out.println(vehicleList);
                  String json = new Gson().toJson(vehicleList);
                  response.setContentType("application/json"); 
                  response.setCharacterEncoding("UTF-8"); 
                  response.getWriter().write(json);
              }
     } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

它有什么不对吗?它甚至没有显示异常。

1 个答案:

答案 0 :(得分:1)

试试这样。

   while (resultSet.next()) {
        latlng=new Latlng();
        String s = resultSet.getString("vehicleno");
        latlng.setVehicleno(resultSet.getString("vehicleno"));
        latlng.setLat(resultSet.getString("lat"));
        latlng.setLat(resultSet.getString("lng"));
        latlng.setLat(resultSet.getString("status"));
        latlng.setLat(resultSet.getString("rdate"));
        latlng.setLat(resultSet.getString("rtime"));
        vehicleList.add(latlng);
    }
    System.out.println(vehicleList);
    String json = new Gson().toJson(vehicleList);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);