Convert JSONArray to List in Java

You can convert a JSONArray to a List using the following method:

  1. Iterate through the JSONArray, convert each of its elements into elements in the List, and then add them to the List.
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;

public class JsonArrayToList {
    public static List<Object> jsonArrayToList(JSONArray jsonArray) {
        List<Object> list = new ArrayList<>();

        try {
            for (int i = 0; i < jsonArray.length(); i++) {
                list.add(jsonArray.get(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }

    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");

        List<Object> list = jsonArrayToList(jsonArray);

        System.out.println(list);
    }
}

In the example above, begin by creating an empty List, then iterate through the elements in the JSONArray, adding each one to the List. Finally, output the converted List.

Note: You need to import the dependency library org.json in order to use the JSONArray class.

bannerAds