How can we add a JSONArray within JSONObject in Java?

JavaJSONObject Oriented ProgrammingProgramming

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"]}
raja
Published on 24-Sep-2019 18:47:01
Advertisements