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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With