JSONObject无法转换为JSONArray,反之亦然?

时间:2014-12-23 23:29:24

标签: java json arrays jsonobject

我正在尝试读取一个json对象(或数组,tbh我不知道这到底是什么)。 无论如何,我要指出我昨天开始使用json数组,很抱歉,如果这是一个简单的问题。

以下是发生的事情:

//doesn’t work

JSONArray valarray = new JSONArray(result);

给出此错误:type org.json.JSONObject cannot be converted to JSONArray

//works

JSONObject jsonObject = new JSONObject(result);

Log.v("RESULTS" , jsonObject.get("results").toString());

//Doesn’t work

JSONObject jsonObject = new JSONObject(result);

JSONObject resultsObject = jsonObject.getJSONObject("results");

给出此错误:type org.json.JSONArray cannot be converted to JSONObject

这是JSON:

{
  "html_attributions" : [],
  "results" : [
    {
      "geometry" : {
        "location" : {
          "lat" : 50.6,
          "lng" : -0.00
        }
      },
      "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
      "id" : "242c6a9664ca28a2",
      "name" : "whatever",
      "place_id" : "ChIJ6xum8T",
      "reference" : "CoQBdQAAAIp",
      "scope" : "GOOGLE",
      "types" : [ "establishment" ],
      "vicinity" : "United Kingdom"
    }
  ],
  "status" : "OK"
}

我想如何在lat内获取lnggeometry

1 个答案:

答案 0 :(得分:1)

您的JSON由object组成。 object包含名为results的数组。该数组包含object个元素。数组中的每个object都包含一个名为object的{​​{1}}。该对象包含名为geometry的{​​{1}}。 object包含locationobject个浮点值。

所以,你的代码应该是这样的:

lat

由于您正在处理数组,因此您可以像这样迭代它:

lng
相关问题