- Trending Categories
- 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 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"]}
Advertisements