{
"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
}]
}
I have access to the "resource" JSON Array at this point, but am unsure as to how I'd get the "lat" and "lon" values within a for loop. Sorry if this description isn't too clear, I'm a bit new to programming.
-
1Welcome to Stack Overflow. I highly recommend you take the tour to learn how Stack Overflow works and read How to Ask. This will help you to improve the quality of your questions. For every question, please show the attempts you have tried and the error messages you get from your attempts.McPringle– McPringle2021年11月06日 10:39:04 +00:00Commented Nov 6, 2021 at 10:39
-
1Btw: Your JSON is invalid. Take a look at the line with the speed property.McPringle– McPringle2021年11月06日 10:40:05 +00:00Commented Nov 6, 2021 at 10:40
-
You need to parse JSON, store it in some object and then access the lat and lon. I know one library from Java docs.oracle.com/javaee/7/api/javax/json/package-summary.html, not sure if it will work for Android.kiner_shah– kiner_shah2021年11月06日 10:40:36 +00:00Commented Nov 6, 2021 at 10:40
2 Answers 2
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
answered Nov 6, 2021 at 10:54
Michael Bahl
3,7071 gold badge15 silver badges20 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use the ObjectMapper class to do this.
- Add dependency for
Jacksonpackage into yourbuild.gradle - Define your JSON response class like this ...
class MyJsonResponse {
List<MyResource> resource;
}
class MyResource {
Double lat;
Double lon;
}
- Create an instance of the object mapper class like this and use it
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)
}
answered Nov 6, 2021 at 10:57
Arthur Klezovich
2,7551 gold badge18 silver badges22 bronze badges
Comments
lang-java