【问题标题】:JSONObject cannot be converted to JSONArray and vice versa?JSONObject 不能转换为 JSONArray,反之亦然?
【发布时间】:2014-12-23 23:29:24
【问题描述】:

我正在尝试读取一个 json 对象(或数组,我不确定这到底是什么)。 无论如何,我要指出我昨天开始使用 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"
}

例如,我想如何在geometry 中获取latlng

【问题讨论】:

  • 我重新格式化了您的 JSON,以便您可以更轻松地查看各个级别。
  • 您不能将 JSON 对象转换为 JSON 数组,反之亦然。它们是不同的东西。访问 json.org 并学习 JSON 语法——学习只需 5-10 分钟。
  • 并确保查看json.org/java 上的 Java 特定文档。
  • latlng 不是(直接)在 geometry 中。它们位于对象location 内部,该对象位于对象geometry 内部,该对象位于作为数组results 的第零个元素的对象内部。
  • @RemyLebeau - 错了!!那不会教他 JSON 语法。

标签: java json arrays jsonobject


【解决方案1】:

您的 JSON 包含一个 objectobject 包含一个名为 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");
    //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 2011-10-08
    • 2020-10-24
    • 2013-03-15
    • 2014-01-23
    • 2019-09-19
    • 2013-12-29
    • 2011-09-22
    相关资源
    最近更新 更多