【发布时间】:2019-06-04 23:02:37
【问题描述】:
我在这里开始了一个关于解析嵌套数组的线程: How do you return the contents of the following nested JSON Array in Android?
我正在从以下网址下载地铁站列表: https://api.tfl.gov.uk/Line/victoria/Route/Sequence/inbound?serviceTypes=Regular,Night
这些站点包含在一个嵌套数组中。我需要从嵌套在“stopPointSequences”数组中的“stopPoint”数组中提取“id”和“name”。我正在使用 AsyncTask 并将列表存储在 RecyclerView 适配器中。我没有使用 HashMap 或 GSON。仅显示一到四个项目。
应用程序没有崩溃,但上面的索引错误出现在这一行(代码如下): JSONObject innerElem = stopPointArrayList.getJSONObject(i);
此外,上面的“for”语句的警告是它“语句有空体”。我遇到了这个帖子:
Error org.json.JSONException: Index 2 out of range
我在嵌套的“for”语句中将“i”更改为“j”,但无法识别“j”。
提前谢谢你。
致版主。如果我发布一个指向我的另一个线程的链接并且不在这里复制和粘贴所有代码,可以吗?
JSONUtils 类:
public static ArrayList<Stations> extractFeatureFromStationJson(String stationJSON)
{
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(stationJSON))
{
return null;
}
ArrayList<Stations> stations = new ArrayList<>();
try
{
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(stationJSON);
JSONArray stopPointSequenceArrayList = baseJsonResponse.getJSONArray("stopPointSequences");
if (stopPointSequenceArrayList != null)
{
for (int i = 0; i < stopPointSequenceArrayList.length(); i++)
{
JSONObject elem = stopPointSequenceArrayList.getJSONObject(i);
if (elem != null)
{
JSONArray stopPointArrayList = elem.getJSONArray("stopPoint");
if (stopPointArrayList != null) {
for (int j = 0; j < stopPointArrayList.length(); j++) ;
{
JSONObject innerElem = stopPointArrayList.getJSONObject(j);
if (innerElem != null) {
String idStation = "";
if (innerElem.has("id")) {
idStation = innerElem.optString(KEY_STATION_ID);
}
String nameStation = "";
if (innerElem.has("name")) {
nameStation = innerElem.optString(KEY_STATION_NAME);
}
Stations station = new Stations(idStation, nameStation);
stations.add(station);
}
}
}
}
}
}
} catch (JSONException e)
{
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing stations JSON results", e);
}
// Return the list of stations
return stations;
}
}
【问题讨论】:
标签: android arrays json parsing multidimensional-array