1

How to create JsonArray and JsonObject in JsonObject

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

Thank for your help :)

3
  • @ꜱᴜʀᴇꜱʜᴀᴛᴛᴀ i edited a topic post ,sorry Commented Aug 11, 2017 at 17:44
  • The docs show you how to build docs.oracle.com/javaee/7/api/javax/json/JsonObject.html have you tried to do it yet? Commented Aug 11, 2017 at 17:45
  • 1
    Which JSON library/package are you using? Commented Aug 11, 2017 at 17:54

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.