【发布时间】: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 中获取lat 和lng?
【问题讨论】:
-
我重新格式化了您的 JSON,以便您可以更轻松地查看各个级别。
-
您不能将 JSON 对象转换为 JSON 数组,反之亦然。它们是不同的东西。访问 json.org 并学习 JSON 语法——学习只需 5-10 分钟。
-
并确保查看json.org/java 上的 Java 特定文档。
-
lat和lng不是(直接)在geometry中。它们位于对象location内部,该对象位于对象geometry内部,该对象位于作为数组results的第零个元素的对象内部。 -
@RemyLebeau - 错了!!那不会教他 JSON 语法。
标签: java json arrays jsonobject