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


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

Updated on: 06-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements