Convert Json Array to normal Java list

JavaAndroidJson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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)

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

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.

Solution 16 - Java

How about using java.util.Arrays?

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHouston we have a problemView Question on Stackoverflow
Solution 1 - JavaPentium10View Answer on Stackoverflow
Solution 2 - JavaNickView Answer on Stackoverflow
Solution 3 - JavaStaxManView Answer on Stackoverflow
Solution 4 - JavaGuido SabatiniView Answer on Stackoverflow
Solution 5 - JavaSamuel PhilippView Answer on Stackoverflow
Solution 6 - JavanurnachmanView Answer on Stackoverflow
Solution 7 - JavapchotView Answer on Stackoverflow
Solution 8 - JavaThiagoView Answer on Stackoverflow
Solution 9 - Javaceph3usView Answer on Stackoverflow
Solution 10 - JavaIman MarashiView Answer on Stackoverflow
Solution 11 - Javauser10878560View Answer on Stackoverflow
Solution 12 - JavaMayank YadavView Answer on Stackoverflow
Solution 13 - JavaStackOverflowView Answer on Stackoverflow
Solution 14 - Javauser1659299View Answer on Stackoverflow
Solution 15 - JavaJohannes BaropView Answer on Stackoverflow
Solution 16 - JavaMichal TsadokView Answer on Stackoverflow