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

My JSON string looks like this (contained in a string variable called sJSON):

[
    {"id":284}
],
[
    {"name":John,"surname":Doe},
    {"name":Jane,"surname":Doe}
]

I'm able to parse the first array like this (using Java and importing org.json):

JSONArray arrJSON = new JSONArray(sJSON);
JSONObject jsonGeneralData = new JSONObject(arrJSON.get(0).toString());

String sResult = jsonGeneralData.get("id").toString();

That returns the expected result, which is 284. I'm struggling to get the second array of items, and iterate through them. I'm not sure if my JSON string is malformed, or if I'm trying to access it the wrong way. Here's what I tried:

JSONObject jsonPersonData = new JSONObject(arrJSON.get(1).toString());

This is as far as I got, I can't figure out how to loop through the individual items inside the second array. I'm new to Android and Java, if anyone could point me in the right direction, it would be greatly appreciated.

EDIT:

It seems that this line only parses the first string in the square brackets:

JSONArray arrJSON = new JSONArray(sJSON);

Either the JSON is wrong (same example as above), or it's not parsing it correctly? I've managed to solve the problem by doing a split on the string and put them each in their own JSONArray, but I don't think that's the best way of doing things.

Any ideas are welcome!

share|improve this question
Updated the original post with more info. – Mr. Smith Jan 22 '12 at 19:33

3 Answers

up vote 2 down vote accepted

You want something like this..

JSONArray jsonArray = new JSONArray(sJSON);
JSONArray jsonPersonData = jsonArray.getJSONArray(1);
for (int i=0; i<jsonPersonData.length(); i++) {
    JSONObject item = jsonPersonData.getJSONObject(i);
    String name = item.getString("name");
    String surname = item.getString("surname");
}
share|improve this answer

You should access the data using the arrJson object, not creating new JSONObjects with the string results of them.

share|improve this answer

You shoul not use JSONObject.toString. This is how you should iterate your array:

for(int i=0;i<arrJSON.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String name =json_data.getString("name");
String surname =json_data.getString("surname"); 
}
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.