Convert Json Array to normal Java list

Viewed 274256

Is there a way to convert JSON Array to normal Java Array for android ListView data binding?

16 Answers

Using Java Streams you can just use an IntStream mapping the objects:

JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
        .mapToObj(array::get)
        .map(Object::toString)
        .collect(Collectors.toList());
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
    if (jsonArray != null) {
        String[] stringsArray = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            stringsArray[i] = jsonArray.getString(i);
        }
        return stringsArray;
    } else
        return null;
}

We can simply convert the JSON into readable string, and split it using "split" method of String class.

String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");

To improve Pentium10s Post:

I just put the elements of the JSON array into the list with a foreach loop. This way the code is more clear.

ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
jsonArray.forEach(element -> list.add(element.toString());

You can use iterator:

JSONArray exportList = (JSONArray)response.get("exports");
Iterator i = exportList.iterator();
while (i.hasNext()) {
      JSONObject export = (JSONObject) i.next();
      String name = (String)export.get("name");
}

I know that the question was for Java. But I want to share a possible solution for Kotlin because I think it is useful.

With Kotlin you can write an extension function which converts a JSONArray into an native (Kotlin) array:

fun JSONArray.asArray(): Array<Any> {
    return Array(this.length()) { this[it] }
}

Now you can call asArray() directly on a JSONArray instance.

Related