
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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"]
Advertisements