Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

4 Answers

up vote 33 down vote accepted
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());
   } 
} 
share|improve this answer
3  
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 at 22:03

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) );
}
share|improve this answer
2  
.size() should be .length() – vaskin Nov 11 '10 at 15:25
1  
Sorry, you're right - I'm confusing Lists with JSONArrays :) It is indeed JSONArray.length(). – Nick Nov 13 '10 at 15:03
thank you, it's helped.. :D – andikurnia Apr 8 at 4:02

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)

share|improve this answer
2  
Note that you must be absolutely sure that the data doesn't contain your separator char, otherwise you'll end up with corrupt data. – Artemix Nov 22 '12 at 10:03

How about using java.util.Arrays?

List<String> list = Arrays.asList((String[])jsonArray.toArray())
share|improve this answer
Brackets don't match and this doesn't work for me. – Anonymous Apr 29 '12 at 22:27
5  
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(). – javajavajavajavajava Sep 5 '12 at 19:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.