我在这里启动了一个有关解析嵌套数组的线程: 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;
}
}
答案 0 :(得分:0)
您可以使用Volley或Retrofit2等任何客户端从api获取数据
获取数据后,使用Gson库映射数据,然后您可以根据需要使用数据
您将拥有成功的响应侦听器和失败的侦听器