java 数据库 json,Java中来自数据库的Json对象

Can anyone help me how to create a JSON Object from the database?

This is what the JSON output should look like:

{“devicelist”:{

“device”: [

{“id”: “01”, “type”: “CAM”, “name”: “Livingroom”}

{“id”: “15”, “type”: “CAM”, “name”: “Kitchen”}

]

}}

This is my code:

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.

I don't know how to start the JSON coding.

解决方案

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

now jObjDeviceList contains all the data.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值