How can we add a JSONArray to JSONObject in Java?

JavaJSONObject Oriented ProgrammingProgramming

The JSON is a text-based format for exchanging data. It is a lightweight component and language independent. We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method. 

Example

import org.json.*;
import java.util.*;
public class AddJSONArrayToJSONObjTest {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      list.add("Raja");
      list.add("Jai");
      list.add("Adithya");
      JSONArray array = new JSONArray();
      for(int i = 0; i < list.size(); i++) {
         array.put(list.get(i));
      }
      JSONObject obj = new JSONObject();
      try {
         obj.put("Employee Names:", array);
      } catch(JSONException e) {
         e.printStackTrace();
      }
      System.out.println(obj.toString());
   }
}

Output

{"Employee Names:":["Raja","Jai","Adithya"]}
raja
Published on 16-Sep-2019 14:36:42
Advertisements