![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we add a JSONArray to JSONObject in Java?
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"]}
Advertisements