After getting data from mysql, I need to export data as JSON,like the format as follows:
{"Thong tin":[{"Ngay":"2013-06-18","Tinh":"An Giang"},{"Ngay":"2013-06-17","Tinh":"Bình Dương"},{"Ngay":"2013-06-16","Tinh":"Bạc Liêu"}]}
But what i get , it's like
{"Thong tin":[{"Ngay":"2013-06-16","Tinh":"Bạc Liêu"},{"Ngay":"2013-06-16","Tinh":"Bạc Liêu"},{"Ngay":"2013-06-16","Tinh":"Bạc Liêu"}]}
Can you help me fix this error?
My code:
acc = new access();
rs2 = acc.query("select province_Name, date_Expired from thong_tin_khach_hang");
List province_Name = new ArrayList();
List date_Expired = new ArrayList();
try {
while (rs2.next()) {
province_Name.add(rs2.getString(1));
date_Expired.add(rs2.getString(2));
}
} catch (SQLException e) {
try {
acc.con.close();
} catch (SQLException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
JSONObject obj = new JSONObject();
JSONArray jarray = new JSONArray();
try {
JSONObject ob = new JSONObject();
for (int i = 0; i < province_Name.size(); i++) {
ob=new JSONObject();
ob.put("Tinh", province_Name.get(i));
ob.put("Ngay", date_Expired.get(i));
jarray.add(ob);
}
obj.put("Thong tin", jarray);
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
out.print(obj);
解决方案
Here is the code that can help you out:
public String getJSONFromResultSet(ResultSet rs,String keyName) {
Map json = new HashMap();
List list = new ArrayList();
if(rs!=null)
{
try {
ResultSetMetaData metaData = rs.getMetaData();
while(rs.next())
{
Map columnMap = new HashMap();
for(int columnIndex=1;columnIndex<=metaData.getColumnCount();columnIndex++)
{
if(rs.getString(metaData.getColumnName(columnIndex))!=null)
columnMap.put(metaData.getColumnLabel(columnIndex), rs.getString(metaData.getColumnName(columnIndex)));
else
columnMap.put(metaData.getColumnLabel(columnIndex), "");
}
list.add(columnMap);
}
} catch (SQLException e) {
e.printStackTrace();
}
json.put(keyName, list);
}
return JSONValue.toJSONString(json);
}
Pass the resultset and your keyname into argument and get the Json String in response.