从Json Object获取字符串

时间:2017-03-28 09:49:11

标签: android json

我正在尝试从检索值,但我一直收到同样的错误:

  

org.json.JSONObject无法强制转换为org.json.JSONArray

我认为这是因为距离是一个对象,所以如何检索距离并将其添加到,下面是JAVA和JSON代码:

                        if (steps != null) {
                            for (int j = 0; j < steps.length(); j++) {
                                JSONObject singleStep = (JSONObject) steps.get(j);
                                HashMap<String, String> direcao = new HashMap<>();

                                JSONArray distance = (JSONArray) singleStep.get("distance");
                                if (distance != null) {
                                    JSONObject singleDistance = (JSONObject) distance.get(0);
                                    String dist = singleDistance.getString("text");
                                    direcao.put("textDi", dist);
                                }

                                JSONArray duration = (JSONArray) singleStep.get("duration");
                                if (duration != null) {
                                    JSONObject singleDuration = (JSONObject) duration.get(0);
                                    String dura = singleDuration.getString("text");
                                    direcao.put("textDu", dura);
                                }

                                String html = singleStep.getString("html_instructions");
                                direcao.put("html_instructions2", html);
                                listaDirecoes.add(direcao);

                            }
                        }

JSON

steps: [
   {
      distance: {
         text: "0,3 km",
         value: 342
      },
      duration: {},
      end_location: {},
      html_instructions: "Siga <b>sul</b> em direção a <b>N3</b>",
      polyline: {},
      start_location: {},
      travel_mode: "DRIVING"
   },
   {},

4 个答案:

答案 0 :(得分:1)

JSONArray distance =(JSONArray)singleStep.get(“distance”);这里是JSONArray的问题instaed使用JSONObject there.use

JSONObject distance = singleStep.getJSONObject(“distance”);

答案 1 :(得分:1)

距离不是数组,它是Json对象。使用这个

   JSONObject distance = singleStep.getJSONObject("distance");

答案 2 :(得分:0)

JSONArray distance = (JSONArray) singleStep.get("distance");
JSONArray distance = (JSONArray) singleStep.get("duration");

在这里,您已将其定义为 JSONArray ,但在Response中将其 JSONObject

答案 3 :(得分:0)

distance是JSONObject,而不是JSONArray。试试这个:

JSONObject distance = (JSONObject) singleStep.getJSONObject("distance");
                            if (distance != null) {
                                String dist = distance.getString("text");
                                direcao.put("textDi", dist);
                            }