141

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

Sotirios Delimanolis
281k62 gold badges718 silver badges744 bronze badges
asked Aug 3, 2010 at 10:42
1
  • 9
    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) Commented Apr 9, 2015 at 13:56

16 Answers 16

196
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,05934 silver badges39 bronze badges
answered Aug 3, 2010 at 10:54
Sign up to request clarification or add additional context in comments.

5 Comments

for loop is missing the closing parenthesis... tried editing but it's not enough characters to pass approval. oh well! just an FYI.
itz not missing actually, the answerer just pasted a chunk of code with the function's open and closing braces.
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?
Thanks. If one has sring then JSONArray can be created as JSONArray jsonArray = new JSONArray (yourString); rest of the code will remain same.
Depending on the implementation you might need size() instead of length().
63

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) );
}
answered Aug 3, 2010 at 10:57

Comments

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);
answered Dec 29, 2014 at 19:28

1 Comment

To add, ObjectMapper is for Jackson. Use Gson.fromJson method for Gson.
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.8k13 gold badges108 silver badges122 bronze badges
answered Nov 22, 2012 at 9:42

2 Comments

Note that you must be absolutely sure that the data doesn't contain your separator char, otherwise you'll end up with corrupt data.
and the result has to be a string.
7

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());
answered Jul 23, 2019 at 22:22

Comments

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);
}
answered Jul 9, 2015 at 14:19

Comments

2

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());
answered Apr 7, 2021 at 8:41

Comments

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

answered Jul 30, 2014 at 7:40

Comments

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();
...
answered Dec 3, 2014 at 7:19

Comments

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;
}
answered Nov 9, 2016 at 15:35

Comments

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;
 }
answered Jun 23, 2017 at 6:33

Comments

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("\",\"");
answered Jan 18, 2019 at 8:55

Comments

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
5081 gold badge7 silver badges20 bronze badges
answered Jan 7, 2019 at 10:21

Comments

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");
}
answered Sep 3, 2021 at 6:51

Comments

-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.

answered May 21, 2019 at 14:30

Comments

-3

How about using java.util.Arrays?

List<String> list = Arrays.asList((String[])jsonArray.toArray())
juan
82.3k52 gold badges165 silver badges198 bronze badges
answered Oct 4, 2011 at 8:30

2 Comments

I don't see a toArray() method in the JSONArray() docs. json.org/javadoc/org/json/JSONArray.html This question probably wouldn't have been asked if there was a simple toArray().
net.sf.json.JSONArray has the toArray() method so this response works for this JSON library. The question didn't specify the library used.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.