android - 解析没有显式JSONObject的JSONArray

时间:2015-07-11 09:47:58

标签: android arrays json parsing

我知道如何解析看起来像[{...},{...},{...}]的JSON。但这是我的例子,有些事情有点不同:

[{"type":"sometype","presentations":["/files/presentation/presentation.pdf"],"description":"somedescription"},{"type":"sometype","presentations":["/files/presentation/presentation2.pdf"],"description":"somedescription"}]

如何解析来自"演示文稿的数据"这里?我将其作为JSONArray获取,但无法获取值(使用带有该数组的.toString()会返回该值,但使用" \"之前" /& #34;(我的意思是" / files / presentation ..."),所以我无法将其添加到url以显示pdf。而且我不知道如何获取JSONObject从该数组(如果它存在,当然)。

1 个答案:

答案 0 :(得分:0)

String jsonString = "[{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation.pdf\"],\"description\":\"somedescription\"},{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation2.pdf\"],\"description\":\"somedescription\"}]";

try {
    JSONArray jaArray = new JSONArray(jsonString);
    JSONObject firstElement = jaArray.getJSONObject(0);
    JSONArray jaPresentations = firstElement.getJSONArray("presentations");
    String string = jaPresentations.getString(0);

    //or chain it together like so:
    String string2 = jaArray.getJSONObject(1).getJSONArray("presentations").getString(0);

    Log.v("TAG", string);
    Log.v("TAG", string2);

输出:

V/TAG﹕ /files/presentation/presentation.pdf
V/TAG﹕ /files/presentation/presentation2.pdf