Reputation: 1543
Is there a way to convert JSON Array to normal Java Array for android ListView data binding?
Upvotes: 141
Views: 295025
Reputation: 1
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");
}
Upvotes: 0
Reputation: 1
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;
}
Upvotes: 0
Reputation: 136
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());
Upvotes: 2
Reputation: 11032
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());
Upvotes: 7
Reputation: 7796
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.
Upvotes: -2
Reputation: 23
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("\",\"");
Upvotes: 0
Reputation: 5753
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;
}
Upvotes: 0
Reputation: 7474
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;
}
Upvotes: 0
Reputation: 4565
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);
}
Upvotes: 4
Reputation: 116472
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);
Upvotes: 19
Reputation: 13302
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();
...
Upvotes: 0
Reputation: 380
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
Upvotes: 0
Reputation: 191
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)
Upvotes: 11
Reputation: 43
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())
Upvotes: -3
Reputation: 207830
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());
}
}
Upvotes: 195
Reputation: 11535
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) );
}
Upvotes: 63