大家好我试图解析这个LINK的JSON文件。
返回的JSON如下 -
我需要首先遍历 journeys
的所有实例,然后我必须为每个 {循环 legs
{1}} 获取 journeys
指令。正如您所看到的,每个 detailed
的 legs
部分返回 instruction
,最终目标是将这些 string
组合在一起,并将其显示为 string
。因此,对于上述JSON,最终目标是显示 -
Jubilee线向Stratford或North Greenwich
对Edgware的北线,或高Barnet
直到现在我一直在努力浏览 TextView
而没有任何运气。
以下是我一直在努力的代码 -
JSON
我相信我的做法是错误的,我没有把循环弄好。解析和导航的建议以及任何其他方法都将受到高度赞赏!
谢谢!
更新:
答案 0 :(得分:1)
JSONArray journeys = new JSONObject("");
for(int i = 0 ; i < journeys.length() ; i++) { // Traverse journeys
JSONObject journey = journeys.getJSONObject(i); // get journeys(i) -> journey
if(journey.has("legs")) { // if journey has "legs" key
JSONArray legs = journey.getJSONArray("legs"); // get the legs array from journey object
for(int j = 0 ; j < legs.length() ; j++) { // Traverse legs
JSONObject leg = legs.getJSONObject(j); // get legs(j) -> leg
if(leg.has("instruction")) { // if leg has "instruction" key in it
JSONObject instruction = leg.getJSONObject("instruction"); // get instruction jsonObject
String detailed = instruction.optString("detailed", "Fallback detailed"); // get detailed string in instruction object
}
}
}
}
更新
private static class Detail {
String journeyType;
String legType;
String instructionType;
String detail;
public Detail(String journeyType, String legType, String instructionType, String detail) {
this.journeyType = journeyType;
this.legType = legType;
this.instructionType = instructionType;
this.detail = detail;
}
}
... ...
List<Detail> detailList = new ArrayList<>();
JSONArray journeys = new JSONObject("");
for(int i = 0 ; i < journeys.length() ; i++) { // Traverse journeys
JSONObject journey = journeys.getJSONObject(i); // get journeys(i) -> journey
if(journey.has("legs")) { // if journey has "legs" key
JSONArray legs = journey.getJSONArray("legs"); // get the legs array from journey object
for(int j = 0 ; j < legs.length() ; j++) { // Traverse legs
JSONObject leg = legs.getJSONObject(j); // get legs(j) -> leg
if(leg.has("instruction")) { // if leg has "instruction" key in it
JSONObject instruction = leg.getJSONObject("instruction"); // get instruction jsonObject
String journeyType = journey.getString("$type");
String legType = leg.getString("$type");
String instructionType = instruction.getString("$type");
String detailed = instruction.getString("detailed"); // get detailed string in instruction object
detailList.add(new Detail(journeyType, legType, instructionType, detailed));
}
}
}
}
for(Detail detail : detailList) {
TextView textView = new TextView([yourContext]);
textView.setText(detail.detail);
yourContentViewGroup.addView(textView);
// or you can use View.inflate(context, layoutRes, yourContentViewGroup) and design a layout to show other detail instance values
}