ARR.s
ARR.s

Reputation: 769

How to create JsonArray and JsonObject in JsonObject java

How to create JsonArray and JsonObject in JsonObject

{
  "users": [7, 16, 35],
  "group_id": "askskdjejs139d.."
}

Thank for your help :)

Upvotes: 1

Views: 9000

Answers (2)

Johny
Johny

Reputation: 2188

You can do this using org.json Library.

Given below are some examples:

// Creating a json object
JSONObject jsonObj = new JSONObject();

// Adding elements to json object
jsonObj.put("key", "value"); // the value can also be a json object or a json array

// Creating a json object from an existing json string
JSONObject jsonObj = new JSONObject("Your json string");

// Creating a json array
JsonArray jsonArray = new JsonArray();

// Adding a json object to json object to json Array
jsonArray.add(jsonObj);

// Adding json array as an element of json object
jsonObject.put("key", "<jsonArray>");

You can call toString() method of JsonObject or JsonArray to get the String representation of the json object/array.

Upvotes: 1

Jayveer Parmar
Jayveer Parmar

Reputation: 500

You can try the following code:

JSONObject user1 = new JSONObject();
try {
    user1.put("user_id", "7");
    user1.put("group_id", "askskdjejs139d");


} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

JSONObject user2 = new JSONObject();
try {
    user2.put("user_id", "16");
    user2.put("group_id", "askskdjejs139d");


} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


JSONArray jsonArray = new JSONArray();

jsonArray.put(user1);
jsonArray.put(user2);

JSONObject userObj = new JSONObject();
    userObj.put("Users", jsonArray);



String jsonStr = userObj.toString();

    System.out.println("jsonString: "+jsonStr);

Upvotes: 2

Related Questions