【问题标题】:can't take any element from JSONObject in java不能从 java 中的 JSONObject 中获取任何元素
【发布时间】:2016-10-25 22:33:34
【问题描述】:

我从 JSONObject 获取元素时遇到问题。

这是我的代码:

public static void getJSON(){
    String googlemap = "http://maps.googleapis.com/maps/api/geocode/json?address=29.0+35.0&sensor=true";

    HttpResponse httpRespone = GET.sendGetReq(googlemap);
    try {
        //Get Stream and convert it to String
        String inputStreamAsString = convertStreamToString(httpRespone.getEntity().getContent());

        //convert from String to JSONObject
        JSONObject json = new JSONObject(inputStreamAsString);
        String formatted_address = json.getJSONObject("results").getString("formatted_address");


    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

当我打电话给

String formatted_address = json.getJSONObject("results").getString("formatted_address");

我得到 JSONException...

我的 json 在这里: http://maps.googleapis.com/maps/api/geocode/json?address=29.0+35.0&sensor=true json link

我想取“formatted_address”的值。 你能帮帮我吗?

【问题讨论】:

    标签: java android json jsonobject


    【解决方案1】:

    resultsJSONArray

    {}这是JSONObject

    [] 这是一个JSONArray,可以包含X JSONObjects,您可以通过for 循环或索引(如果您知道的话)访问它

    String formatted_address  = json.getJSONArray("results").getJSONObject(0).getString("formatted_address");
    

    【讨论】:

      【解决方案2】:
      JSONObject jsonObject = new JSONObject("your json")
      String formateed_address = jsonObject.getJSONArray("results").
                                 getJSONObject(0).getString("formatted_address");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 1970-01-01
        • 1970-01-01
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多