[java] Convert Json Array to normal Java list

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

This question is related to java android json

The answer is


ArrayList<String> list = new ArrayList<String>();     
JSONArray jsonArray = (JSONArray)jsonObject; 
if (jsonArray != null) { 
   int len = jsonArray.length();
   for (int i=0;i<len;i++){ 
    list.add(jsonArray.get(i).toString());
   } 
} 

we starting from conversion [ JSONArray -> List < JSONObject > ]

public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array) 
        throws JSONException {
  ArrayList<JSONObject> jsonObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           jsonObjects.add(array.getJSONObject(i++)) 
       );
  return jsonObjects;
}

next create generic version replacing array.getJSONObject(i++) with POJO

example :

public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array) 
        throws JSONException {
  ArrayList<Tt> tObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           tObjects.add( (T) createT(forClass, array.getJSONObject(i++))) 
       );
  return tObjects;
}

private static T createT(Class<T> forCLass, JSONObject jObject) {
   // instantiate via reflection / use constructor or whatsoever 
   T tObject = forClass.newInstance(); 
   // if not using constuctor args  fill up 
   // 
   // return new pojo filled object 
   return tObject;
}

I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
    for (Long s : list) {
        System.out.println(s);
    }
}

Works also with array of strings


Maybe it's only a workaround (not very efficient) but you could do something like this:

String[] resultingArray = yourJSONarray.join(",").split(",");

Obviously you can change the ',' separator with anything you like (I had a JSONArray of email addresses)


If you don't already have a JSONArray object, call

JSONArray jsonArray = new JSONArray(jsonArrayString);

Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.

List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );
}

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());

_x000D_
_x000D_
   private String[] getStringArray(JSONArray jsonArray) throws JSONException {_x000D_
            if (jsonArray != null) {_x000D_
                String[] stringsArray = new String[jsonArray.length()];_x000D_
                for (int i = 0; i < jsonArray.length(); i++) {_x000D_
                    stringsArray[i] = jsonArray.getString(i);_x000D_
                }_x000D_
                return stringsArray;_x000D_
            } else_x000D_
                return null;_x000D_
        }
_x000D_
_x000D_
_x000D_


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("\",\"");

You can use a String[] instead of an ArrayList<String>:

Hope it helps!

   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;
        }

Instead of using bundled-in org.json library, try using Jackson or GSON, where this is a one-liner. With Jackson, f.ex:

List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);

Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();


                        adapter.notifyDataSetChanged();

...

How about using java.util.Arrays?

List<String> list = Arrays.asList((String[])jsonArray.toArray())

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.


Use can use a String[] instead of an ArrayList<String>:

It will reduce the memory overhead that an ArrayList has

Hope it helps!

String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
    parametersArray[i] = parametersJSONArray.getString(i);
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?