今天做到一个接口需求,描述下:
mysql数据库里面有6个字段,每个字段有且只有一条记录,需求是将每个字段+值,作为一个JSONObject,最后给他返回一个包含6个JSONObject的JSONArray
开始没有这种想法,只知道javabean+list再转。所以以此纪念下。。。。
Connection conn=DBconnection.getConnection();
String sql="select * from explain_";
ResultSet rs=DBdao.InfoQuery(sql);
JSONObject info1=new JSONObject();
JSONObject info2=new JSONObject();
JSONObject info3=new JSONObject();
JSONObject info4=new JSONObject();
JSONObject info5=new JSONObject();
JSONObject info6=new JSONObject();
if(rs !=null){
try {
while(rs.next()){
info1.put("PriceTypeName",rs.getString("CrossRate1"));
info1.put("PriceTypeId","CrossRate1");
info2.put("PriceTypeName",rs.getString("CrossRate2"));
info2.put("PriceTypeId","CrossRate2");
info3.put("PriceTypeName",rs.getString("CrossRate3"));
info3.put("PriceTypeId","CrossRate3");
info4.put("PriceTypeName",rs.getString("CrossRate4"));
info4.put("PriceTypeId","CrossRate4");
info5.put("PriceTypeName",rs.getString("CrossRate5"));
info5.put("PriceTypeId","CrossRate5");
info6.put("PriceTypeName",rs.getString("CrossRate6"));
info6.put("PriceTypeId","CrossRate6");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JSONArray ja = new JSONArray();
ja.add(info1);
ja.add(info2);
ja.add(info3);
ja.add(info4);
ja.add(info5);
ja.add(info6);
out.println(ja);
out.flush();
out.close();
DBconnection.DBclose();
}