- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 an array to JSON Array using JSON-lib API in Java?n
A Java array is an object which stores multiple variables of the same type, it can hold primitive types and object references whereas JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values, an internal form is an object having get() and opt() methods for accessing the values by index and element() method for adding or replacing values. In the first step, we can create an Object[] array and pass this parameter as an argument to the toJSON() of JSONSerializer class and typecasting it to get the JSON array.
We can convert Object[] array to JSONArray in the below example
Example
import net.sf.json.JSONArray; import net.sf.json.JSONSerializer; public class ConvertArrayToJSONArrayTest { public static void main(String[] args) { Object[] objArray = new Object[] { "Array to JSON Array", new Integer(10), new Long(30), new Double(14.26), true, new char[] {'X', 'Y', 'Z'} }; JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(objArray); System.out.println(jsonArray.toString(3)); //pretty print JSON } }
Output
[ "Array to JSON Array", 10, 30, 14.26, true, [ "X", "Y", "Z" ] ]
- Related Articles
- How to convert an array to JSON Array using JSON-lib API in Java?
- How to convert a JSON array to array using JSON-lib API in Java?
- How to convert a Collection to JSON Array using JSON-lib API in Java?
- How to convert a Map to JSON object using JSON-lib API in Java?
- How to convert a JSON string to a bean using JSON-lib API in Java?
- How to convert the JSON object to a bean using JSON-lib API in Java?
- How to add elements to JSON Object using JSON-lib API in Java?
- How to convert a bean to XML using JSON-lib API in Java?
- How to convert a bean to XML without type hints using JSON-lib API in Java?
- How to convert Java Array/Collection to JSON array?
- How to convert JSON Array to normal Java Array?
- JavaScript Convert an array to JSON
- How to convert XML to JSON array in Java?
- How to convert a JSON array to CSV in Java?
- How can we implement a JSON array using Streaming API in Java?
- How to read/parse JSON array using Java?

Advertisements