开发者

Parsing JSON, not sure on how and when to use iterators (Android Platform)

开发者 https://www.devze.com 2023-01-19 20:39 出处:网络
I have this JSON to parse {\"files_informations\": { \"row\":{\"value\":\"artist1\"}, \"row\":{\"value\":\"artist2\"}

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开发者_如何学Go 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"}
                       ]
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号