You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Java生成含JSON对象的数组,如何通过JS访问?

解决Java与JavaScript跨语言JSON通信的属性访问问题

嘿,我来帮你搞定这个JSON数据访问的问题!先帮你梳理下Java端构建出来的JSON结构,这样你就能更清晰地知道怎么在JS里拿到想要的值了。

首先,你Java代码生成的最终JSON数据结构大概是这样的:

{
  "destination": [
    {
      "lat": 20.000,
      "lon": 20.000
    }
  ]
}

知道了结构之后,在JavaScript里访问就很简单了,分几步来:

1. 先获取数组本身

你可以直接通过.操作符拿到destination数组:

const destinationList = data.destination;

2. 访问数组里的坐标对象

因为你在Java里只往数组里放了一个latLng对象,所以直接取数组的第0个元素就行:

const firstLatLng = destinationList[0];

3. 读取lat和lon属性

现在就可以直接拿到纬度和经度了:

const latitude = firstLatLng.lat;
const longitude = firstLatLng.lon;
console.log('纬度:', latitude); // 输出 20.000
console.log('经度:', longitude); // 输出 20.000

更简洁的链式写法

如果你觉得分步写麻烦,也可以把这些步骤合并成一行:

const lat = data.destination[0].lat;
const lon = data.destination[0].lon;

处理数组有多个元素的情况

要是之后你往destination数组里放多个坐标对象,还可以用遍历的方式批量获取:

data.destination.forEach((latLngItem) => {
  console.log('当前纬度:', latLngItem.lat);
  console.log('当前经度:', latLngItem.lon);
});

最后给你个小建议:如果不确定拿到的data结构是不是符合预期,可以先在JS里打印一下console.log(data),看看实际的JSON结构,这样能更快定位问题~

内容的提问来源于stack exchange,提问作者mostamazingname

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:25:31