0

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"));
}
2
  • what's wrong building a new JSONArray with a good 'ol fashioned for loop? Commented Apr 19, 2012 at 2:23
  • See this post. This will help you. stackoverflow.com/questions/2487841/… Commented Apr 19, 2012 at 2:25

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.