views:

72

answers:

1

Hi all,

I have this JSON to parse

{"files_informations": {
                         "row":{"value":"artist1"},
                         "row":{"value":"artist2"}
                       }
}

I would like to know how can I get the first value artist1 and then the second one artist2

This is what I am doing :

JSONObject myObject = jObject.getJSONObject("files_informations");
JSONObject rowObject = myObject.getJSONObject("row");
Iterator<JSONObject> rowIt = rowObject.keys();

while (rowIt.hasNext()) {
     JSONObject tmp = rowIt.next();             
     Log.e("", tmp.getString("value"));
}

I got java.lang.classCastException for this JSONObject tmp = rowIt.next();

So there are my two questions :

  • Do I need to use iterators in this case ?
  • How do one should use them ?

Edit :

Should the JSON looks like this ?

{"files_informations": [
                         "row":{"value":"artist2"},
                         "row":{"value":"artist1"}
                       ]
}
+1  A: 

rowIt.next() is "row" String in this case.

Refactor your JSON to this:

{"files_informations":
  [ {"value":"artist2"},
    {"value":"artist1"} ] }

Or even this:

{ "files_informations": [ "artist2", "artist1" ] } 

and then use:

JSONArray artistsArr = myObject.getJSONArray("files_informations");
for (int i = 0; i < artistsArr.size(); i++) {
     // first case
     Log.d(TAG, artistsArr.get(i).getString("value"));
     // Second case
     Log.d(TAG, artistsArr.getString(i));
}

Iterators are not supported in JSONArrays, however you can convert them to plain Java arrays/lists if you really need it.

shaman.sir