Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json object from database in java

Tags:

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.

like image 656
bharathi Avatar asked Jul 20 '11 09:07

bharathi


1 Answers

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.

like image 104
MByD Avatar answered Oct 31 '22 18:10

MByD