如何在Android Studio中用Volley在Kotlin中解析嵌套JSON对象
提取Google Places API嵌套JSON中的坐标信息
你遇到的问题是直接访问location字段报错,因为它不是顶层字符串,而是嵌套在geometry对象里的子对象。正确的做法是逐层解析嵌套的JSONObject:
关键步骤:
- 先从顶层对象中获取
geometry对应的JSONObject - 再从
geometry中获取location对应的JSONObject - 最后从
location中提取lat(纬度)和lng(经度),注意这两个是数值类型,要用getDouble()而非getString()
另外注意你的请求URL里的fields参数只指定了price_level,Google Places API会仅返回你指定的字段,所以要拿到geometry必须修改fields参数,比如改成fields=name,price_level,geometry,否则API不会返回坐标相关数据。
修改后的代码片段:
fun methodToGetInfo(){ tbUsuarios?.removeAllViews() val queue = Volley.newRequestQueue(this) // 修改fields参数,包含需要的字段 val url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?fields=name,price_level,geometry&location=25.7299374%2C-100.2096866&radius=2500&type=restaurant&key=AIzaSyDV6aFItX960hrbAaI229-8iDa3xTZ-RXU" val myJsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response -> try { val myJsonArray = response.getJSONArray("results") for(i in 0 until myJsonArray.length()){ val myJSONObject = myJsonArray.getJSONObject(i) val registro = LayoutInflater.from(this).inflate(R.layout.table_row_np,null,false) val colName = registro.findViewById<TextView>(R.id.columnaNombre) val colPrice = registro.findViewById<TextView>(R.id.columnaEmail) val colLatitude = registro.findViewById<View>(R.id.colEditar) val colBorrar = registro.findViewById<View>(R.id.colBorrar) // 获取顶层name字段 val name = myJSONObject.getString("name") colName.text = name Log.d(TAG, "Nombre: $name" ) // 获取顶层price_level字段 val priceLevel = myJSONObject.getInt("price_level").toString() colPrice.text = priceLevel Log.d(TAG, "Price Level: $priceLevel" ) // 逐层解析嵌套的坐标字段 val geometryObj = myJSONObject.getJSONObject("geometry") val locationObj = geometryObj.getJSONObject("location") val lat = locationObj.getDouble("lat") val lng = locationObj.getDouble("lng") Log.d(TAG, "Latitude: $lat, Longitude: $lng") tbUsuarios?.addView(registro) } } catch (e: JSONException) { // 捕获JSON解析异常,避免崩溃 Log.e(TAG, "JSON解析错误: ${e.message}") } }, Response.ErrorListener { error -> Log.e(TAG, "请求错误: ${error.message}") }) queue.add(myJsonObjectRequest) }
额外提示:
- 建议使用
optJSONObject()替代getJSONObject(),如果字段不存在时会返回null而非抛出异常,更安全:val geometryObj = myJSONObject.optJSONObject("geometry") geometryObj?.let { val locationObj = it.optJSONObject("location") locationObj?.let { loc -> val lat = loc.optDouble("lat", 0.0) val lng = loc.optDouble("lng", 0.0) Log.d(TAG, "Latitude: $lat, Longitude: $lng") } }
内容的提问来源于stack exchange,提问作者Hans Ricardo Davila Acuña
相关产品推荐
相关产品推荐

