从jsonArray java android Studio获取字符串


{
"resource": [{
"devid": "862057040386432",
" time": "2021-11-02 12:36:30",
"etype": "G_PING",
"engine": "OFF",
"lat": "9.235940",
"lon": "78.760240",
"vbat": "3944",
"speed":"7.49",
"plnt": "10",
"fuel": 0
}]
}

我可以访问";资源";JSON数组,但不确定如何获得";lat">";lon">for循环中的值。很抱歉,如果这个描述不太清楚,我对编程有点陌生。

const data = {
resource: [{
devid: "862057040386432",
time: "2021-11-02 12:36:30",
etype: "G_PING",
engine: "OFF",
lat: "9.235940",
lon: "78.760240",
vbat: "3944",
speed:"7.49",
plnt: "10",
fuel: 0
}
]
};

const latAndLongVersionOne = data.resource.map(res => [res.lat, res.lon]);
const latAndLongVersionTwo = data.resource.map(({lat, lon}) => [lat, lon]);
const latAndLongVersionThree = data.resource.map(({lat, lon}) => ({lat, lon}));
console.log('Lat and long: ', latAndLongVersionOne); // Nested array with long and lat (values names has to be inferred)
console.log('Lat and long: ', latAndLongVersionTwo); // Same result with another syntax
console.log('Lat and long: ', latAndLongVersionThree); // Array of objects with caption

您可以使用ObjectMapper类来执行此操作。

  1. Jackson包的依赖项添加到build.gradle
  2. 像这样定义JSON响应类
class MyJsonResponse {
List<MyResource> resource;
}
class MyResource {
Double lat;
Double lon;
}
  1. 创建这样的对象映射器类的实例并使用它
var mapper = new ObjectMapper()
var jsonString = // obtain your JSON string somehow
// Convert JSON string to object
var myResponse= objectMapper.readValue(jsonCarArray,MyJsonResponse.class)
for(var resource : myResponse.resources) {
// Here you get the values
print(resource.lat + " " + resource.lon)
}

最新更新