java根据mysql的数据创建json对象 [英] Create json Object by java from data of mysql
本文介绍了java根据mysql的数据创建json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从mysql获取数据后,需要将数据导出为JSON,格式如下:
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"}]}
但我得到的,就像
{"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?
我的代码:
acc = new access();
rs2 = acc.query("select province_Name, date_Expired from thong_tin_khach_hang");
List<String> province_Name = new ArrayList<String>();
List<String> date_Expired = new ArrayList<String>();
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<String,Object> columnMap = new HashMap<String, Object>();
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);
}
将结果集和您的键名传递给参数并获得 Json 字符串作为响应.
Pass the resultset and your keyname into argument and get the Json String in response.
这篇关于java根据mysql的数据创建json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文