137

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 8
    The funny thing is that `org.JSONArray` uses an ArrayList under the hood... `The arrayList where the JSONArray's properties are kept`, so most looping is done for nothing in many cases (just for the encapsulation) – Christophe Roussy Apr 09 '15 at 13:56

16 Answers16

193
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());
   } 
} 
Tushar
  • 8,019
  • 31
  • 38
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • 6
    for loop is missing the closing parenthesis... tried editing but it's not enough characters to pass approval. oh well! just an FYI. – Matt K Sep 21 '11 at 17:09
  • itz not missing actually, the answerer just pasted a chunk of code with the function's open and closing braces. – Sarim Javaid Khan Mar 16 '13 at 22:03
  • 1
    What happens if `jsonArray.get(i)` returns null (as a result of parsing this: `[ "String 1", null, "String 2" ]`)? Wouldn't your for-loop crash then? – dbm Sep 23 '13 at 12:20
  • Thanks. If one has sring then JSONArray can be created as JSONArray jsonArray = new JSONArray (yourString); rest of the code will remain same. – Kaushik Lele Mar 08 '15 at 13:12
  • Depending on the implementation you might need `size()` instead of `length()`. – Guillaume F. Sep 03 '19 at 05:53
62

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) );
}
Nick
  • 11,475
  • 1
  • 36
  • 47
19

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);
StaxMan
  • 113,358
  • 34
  • 211
  • 239
11

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)

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Guido Sabatini
  • 191
  • 2
  • 7
6

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());
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
4

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);
}
nurnachman
  • 4,468
  • 2
  • 37
  • 40
1

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());
StackOverflow
  • 116
  • 1
  • 6
0

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

pchot
  • 380
  • 3
  • 14
0

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

...
Thiago
  • 12,778
  • 14
  • 93
  • 110
0

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;
}
ceph3us
  • 7,326
  • 3
  • 36
  • 43
0

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;
        }
Iman Marashi
  • 5,593
  • 38
  • 51
0
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;
}
np_6
  • 514
  • 1
  • 6
  • 19
0

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

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");
}
-2

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.

Johannes Barop
  • 7,323
  • 2
  • 25
  • 33
-3

How about using java.util.Arrays?

List<String> list = Arrays.asList((String[])jsonArray.toArray())
juan
  • 80,295
  • 52
  • 162
  • 195
  • 15
    I don't see a `toArray()` method in the `JSONArray()` docs. http://www.json.org/javadoc/org/json/JSONArray.html This question probably wouldn't have been asked if there was a simple `toArray()`. – javajavajavajavajava Sep 05 '12 at 19:01
  • 1
    net.sf.json.JSONArray has the toArray() method so this response works for this JSON library. The question didn't specify the library used. – ilinca Aug 03 '15 at 11:46