简体   繁体   中英

how to create json object with multiple array within it using org.json.JSONObject package in java?

I want to create json object as, {"jsonName":[{"id":"1","name":"abc"},{"id":2,"name":"pqr"}]} "jsonName" fetch the data from database and I want to create the object from that data. and I want to update some value from that json object with "id" after we created that.

Suppose I run the query from java..

String selectStr = "select * from emp";
ResultSet rs = ps.executeQuery ();
while(rs.next())
{
.....
}

I'm fetching data like this and wants to create and json object that store all the data rows. can someone please help me .. I'm new to json object.

You can try quick-json . Which can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. quick-json can work with any arbitrary Java objects.

When using a library such as gson (see: https://github.com/google/gson ) doing this becomes a trivial task. You can simply define a structure in the shape of classes such as this:

public class JsonObj {
    public List<JsonItem> jsonName;
}

public class JsonItem {
    public int id;
    public String name;
}

Then, you can use gson to serialize your object into json (exhaustive example, but you get the point):

Gson gson = new Gson();
JsonObj obj = new JsonObj();
obj.jsonName = new ArrayList<String>();

String selectStr = "select * from emp";
ResultSet rs = ps.executeQuery();
while(rs.next())
{
    JsonItem item = new JsonItem();
    item.id = rs.getInt(1); //or whatever column index goes here
    item.name = rs.getString(2); //or whatever column index goes here
    obj.jsonName.Add(item);
}
String json = gson.toJson(obj);

json object will now contain the serialized json in String format.

Using org.json library:

JSONArray elements  = new JSONArray();
JSONObject rootJson = new JSONObject();
String selectStr    = "select * from emp";
try
{
    JSONArray elements  = null; // to prevent query returning empty resultset
    JSONArray el        = new JSONArray();

    ResultSet rs = ps.executeQuery();
    while(rs.next())
    {
        JSONObject el = new JSONObject();
        el.put("id", rs.getInt(1));
        el.put("name", rs.getString(2));
        elements.put(element);
    }

    rootJson.put("jsonName", elements);

}catch(Exception e)
{
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM