How can we add a JSONArray within JSONObject in Java?


A JSONObject can parse text from a String to produce a map-like object and a JSONArray can parse text from a String to produce a vector-like object. We can also add a JSONArray within JSONObject by first creating a JSONArray with few items and add these array of items to the put() method of JSONObject class.

Syntax

public JSONObject put(java.lang.String key, java.util.Collection<?> value) throws JSONException

Example

import org.json.*;
public class AddJSONArrayTest {
   public static void main(String[] args) throws JSONException {
      JSONArray array = new JSONArray();
      array.put("INDIA");
      array.put("AUSTRALIA");
      array.put("ENGLAND");
      JSONObject obj = new JSONObject();
      obj.put("COUNTRIES", array);
      System.out.println(obj);
   }
}

Output

{"COUNTRIES":["INDIA","AUSTRALIA","ENGLAND"]}

Updated on: 04-Jul-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements