0
{
    "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.

Gn Deepan
  • 11
  • 5
  • 1
    Welcome to Stack Overflow. I highly recommend you take the [tour](https://stackoverflow.com/tour) to learn how Stack Overflow works and read [How to Ask](https://stackoverflow.com/questions/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 Nov 06 '21 at 10:39
  • 1
    Btw: Your JSON is invalid. Take a look at the line with the speed property. – McPringle Nov 06 '21 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 https://docs.oracle.com/javaee/7/api/javax/json/package-summary.html, not sure if it will work for Android. – kiner_shah Nov 06 '21 at 10:40

2 Answers2

0
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
Michael Bahl
  • 2,941
  • 1
  • 13
  • 16
0

You can use the ObjectMapper class to do this.

  1. Add dependency for Jackson package into your build.gradle
  2. Define your JSON response class like this ...
class MyJsonResponse {
  List<MyResource> resource;
}

class MyResource {
 Double lat;
 Double lon;
}
  1. 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)
}
Arthur Klezovich
  • 2,595
  • 1
  • 13
  • 17