How can we convert a JSONArray to String Array in Java?

JavaJSONObject Oriented ProgrammingProgramming

The JSON is one of the widely used data-interchange formats. It is a lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface.

We can convert a JSONArray to String Array in the below example

Example

import org.json.*;
import java.util.*;
public class JsonArraytoStringArrayTest {
   public static void main(String[] args) {
      JSONArray jsonArray = new JSONArray();
      jsonArray.put("INDIA ");
      jsonArray.put("AUSTRALIA ");
      jsonArray.put("SOUTH AFRICA ");
      jsonArray.put("ENGLAND ");
      jsonArray.put("NEWZEALAND ");
      List<String> list = new ArrayList<String>();
      for(int i=0; i < jsonArray.length(); i++) {
         list.add(jsonArray.getString(i));
      }
      System.out.print("JSONArray: " + jsonArray);
      System.out.print("\n");
      String[] stringArray = list.toArray(new String[list.size()]);
      System.out.print("String Array: ");
      for(String str : stringArray) {
         System.out.print(str);
      }
   }
}

Output

JSONArray: ["INDIA ","AUSTRALIA ","SOUTH AFRICA ","ENGLAND ","NEWZEALAND "]
String Array: INDIA AUSTRALIA SOUTH AFRICA ENGLAND NEWZEALAND
raja
Published on 14-Oct-2019 18:36:29
Advertisements