- 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 to convert Java Array/Collection to JSON array?
Google provides a library named org.json.JSONArray and, following is the maven dependency to add library to your project.
<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1</version> </dependency>
The JSONArray class of the org.json package provides put() method. Using this method, you can populate the JSONArray object with the contents of the elements.
Example
import org.json.JSONArray; public class ArrayToJson { public static void main(String args[]) { String [] myArray = {"JavaFX", "HBase", "JOGL", "WebGL"}; JSONArray jsArray = new JSONArray(); for (int i = 0; i < myArray.length; i++) { jsArray.put(myArray[i]); } System.out.println(jsArray); } }
Output
["JavaFX","HBase","JOGL","WebGL"]
In the same way you can pass a collection object to the constructor of the JSONArray class.
Example
import java.util.ArrayList; import org.json.JSONArray; public class ArrayToJson { public static void main(String args[]) { ArrayList <String> arrayList = new ArrayList<String>(); arrayList.add("JavaFX"); arrayList.add("HBase"); arrayList.add("JOGL"); arrayList.add("WebGL"); JSONArray jsArray2 = new JSONArray(arrayList); System.out.println(jsArray2); } }
Output
["JavaFX","HBase","JOGL","WebGL"]
- Related Articles
- How to convert a Collection to JSON Array using JSON-lib API in Java?
- How to convert JSON Array to normal Java Array?
- How to convert an array to JSON Array using JSON-lib API in Java?\n
- How to convert a JSON array to array using JSON-lib API in Java?\n
- How to convert XML to JSON array in Java?
- Java Program to Convert Collection into Array
- Java Program to Convert Array into Collection
- How to convert a JSON array to CSV in Java?
- JavaScript Convert an array to JSON
- How to convert JSON string to array of JSON objects using JavaScript?
- How can we convert a list to the JSON array in Java?
- How to convert a List to JSON array using the Jackson library in Java?
- How to read/parse JSON array using Java?
- how to convert Object array to String array in java
- How to convert Java Array to Iterable?

Advertisements