gpt4 book ai didi

java - java从mysql的数据创建json对象

转载 作者:行者123 更新时间:2023-11-30 07:16:15 24 4
gpt4 key购买 nike

从mysql中获取数据后,需要将数据导出为JSON格式,格式如下:

{"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"}]}

你能帮我解决这个错误吗?

我的代码:

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);

最佳答案

下面是可以帮助您解决问题的代码:

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 字符串作为响应。

关于java - java从mysql的数据创建json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17160351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com