Java中来自数据库的Json对象 [英] Json object from database in java
本文介绍了Java中来自数据库的Json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮助我如何从数据库创建JSON对象吗?
Can anyone help me how to create a JSON Object from the database?
JSON输出应如下所示:
{"devicelist":{
"device": [
{"id": "01", "type": "CAM", "name": "Livingroom"}
{"id": "15", "type": "CAM", "name": "Kitchen"}
]
}}
这是我的代码:
if (reg!=null)
{
try
{
con = ds.getConnection();
Statement select = con.createStatement();
ResultSet result=select.executeQuery("Select type,name,demo from register_device");
while (result.next())
{
String type_json=result.getString("type");
String name_json=result.getString("name");
String id_json=result.getString("demo");
JSONArray arrayObj=new JSONArray();
}
}
catch(Exception e)
{
}
}
我能够从数据库中获取选定的类型,名称,演示.
I am able to get the selected type,name,demo from the database.
我不知道如何开始JSON编码.
I don't know how to start the JSON coding.
推荐答案
如果您想从数据库中提取数据并自己构造JSON对象,则可以执行以下操作:
If you want to extract the data from the DB and construct the JSON Object yourself, you can do:
JsonArray jArray = new JsonArray();
while (result.next())
{
String type_json=result.getString("type");
String name_json=result.getString("name");
String id_json=result.getString("demo");
JsonObject jObj = new JsonObject();
jobj.put("id", id_json);
jobj.put("type", type_json);
jobj.put("name", name_json);
jArray.put(jObj);
}
JsonObject jObjDevice = new JsonObject();
jObjDevice.put("device", jArray);
JsonObject jObjDeviceList = new JsonObject();
jObjDevice.put("devicelist", jObjDevice );
现在jObjDeviceList
包含所有数据.
这篇关于Java中来自数据库的Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文