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

I need to be able to create a new JSONArray from the one I already have, in the array I have a whole lot of fields called id, another one on each line, how do I get a list of them?

eg. I get this back

[{"id":111,"users":"blob"},
 {"id":111,"users":"blob"},
 {"id":111,"users":"blob"},
 {"id":111,"users":"blob"},
 {"id":111,"users":"blob"},
 {"id":111,"users":"blob"}]

How would I get a list of just the ID's ?


  • Edit

Decided to use a for loop straight after this but thanks :D

HttpResponse response = httpclient.execute(httpget); //execute the HttpPost request
JSONArray jsa =  projectResponse(response); //get the json response

for(int i = 0; i < jsa.length(); i++){
    JSONObject jso = jsa.getJSONObject(i);
    publishProgress(jso.getString("id"), jso.getString("name"));
}
share|improve this question
what's wrong building a new JSONArray with a good 'ol fashioned for loop? – Travis Webb Apr 19 '12 at 2:23
See this post. This will help you. stackoverflow.com/questions/2487841/… – Akilan Apr 19 '12 at 2:25

1 Answer

up vote 1 down vote accepted

Try this out:

JSONArray yourJSONArray;
List<String> tempIDStringCollection = new List<String>();
...

for(int i = 0; i < yourJSONArray.length(); i++){
        String id = yourJSONArray.getJSONObject(i).getString("id");
        tempIDStringCollection.add(id);
}

Then to transfer this into another JSONArray, try:

JSONArray newArray = new JSONArray(tempIDStringCollection);

To skip the List creation, try

JSONArray yourJSONArray;
JSONArray newArray = new JSONArray();
...

for(int i = 0; i < yourJSONArray.length(); i++){
        String id = yourJSONArray.getJSONObject(i).getString("id");
        newArray.put(i, id);
}
share|improve this answer

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.