有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSONObject不能转换为JSONArray,反之亦然?

我试图读取一个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"
}

例如,我应该如何获得latlng内部的geometry


共 (1) 个答案

  1. # 1 楼答案

    JSON由object组成。该object包含一个名为results的数组。数组包含object个元素。数组中的每个object都包含一个名为geometryobject。该对象包含一个名为locationobjectobject包含latlng浮点值

    因此,您的代码应该如下所示:

    String json = ...;
    JSONObject JsonObj = new JSONObject(json);
    JSONArray ResultArr = JsonObj.getJSONArray("result");
    JSONObject ResultObj = ResultArr.getJSONObject(0);
    JSONObject Geometry = ResultObj.getJSONObject("geometry");
    JSONObject Location = Geometry.getJSONObject("location");
    double Latitude = Location.getDouble("lat");
    double Longitude = Location.getDouble("lng");
    

    由于您处理的是一个数组,因此可以像这样对其进行迭代:

    String json = ...;
    JSONObject JsonObj = new JSONObject(json);
    JSONArray ResultArr = JsonObj.getJSONArray("result");
    int count = ResultArr.length();
    for (int i = 0; i < count; ++i)
    {
        JSONObject ResultObj = ResultArr.getJSONObject(i);
        JSONObject Geometry = ResultObj.getJSONObject("geometry");
        JSONObject Location = Geometry.getJSONObject("location");
        double Latitude = Location.getDouble("lat");
        double Longitude = Location.getDouble("lng");
        //...
    }