JSON stands for JavaScript Object Notation. It is one of the widely used formats for exchanging data through web applications. JSON arrays are almost the same as arrays in JavaScript. They can be understood as a collection of indexed data (strings, numbers, Boolean values). Given a JSON array, we will discuss how to convert it to a String array in Java.
Creating a JSON array
Let's start by creating a JSON array in Java. Here, we will use some sample data to input into the array, but you can use the data as needed.
1. Defining the array
JSONArray exampleArray = new JSONArray();
Please note that we will import the org.json package to use this command. This will be discussed in the code later.
2. Inserting data into the array
We now add some example data into the array.
exampleArray.put("Geeks "); exampleArray.put("For "); exampleArray.put("Geeks ");
Note the spaces given after each string. This is done because when we convert it to a String array, we want to make sure that there is space between each element.
Conversion into a String array
1. Creating a List
Let’s start by creating a List.
List exampleList = new ArrayList();
2. Adding JSON array data into the List
We can loop through the JSON array to feature all elements to our List.
for(int i=0; i< exampleArray.length; i++){ exampleList.add(exampleArray.getString(i)); }
3. Getting String array as output
We can loop through the JSON array to add all elements to our List.
int size = exampleList.size(); String[] stringArray = exampleList.toArray(new String[size]);
Implementation:
// importing the packages import java.util.*; import org.json.*; public class GFG { public static void main(String[] args) { // Initialising a JSON example array JSONArray exampleArray = new JSONArray(); // Entering the data into the array exampleArray.put("Geeks "); exampleArray.put("For "); exampleArray.put("Geeks "); // Printing the contents of JSON example array System.out.print("Given JSON array: " + exampleArray); System.out.print("\n"); // Creating example List and adding the data to it List exampleList = new ArrayList(); for (int i = 0; i < exampleArray.length; i++) { exampleList.add(exampleArray.getString(i)); } // Creating String array as our // final required output int size = exampleList.size(); String[] stringArray = exampleList.toArray(new String[size]); // Printing the contents of String array System.out.print("Output String array will be : "); for (String s : stringArray) { System.out.print(s); } } }
Output:
Given JSON array: ["Geeks ","For ","Geeks "] Output String array will be : Geeks For Geeks