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.

3
  • 1
    Welcome 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. Commented Nov 6, 2021 at 10:39
  • 1
    Btw: Your JSON is invalid. Take a look at the line with the speed property. Commented 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. Commented Nov 6, 2021 at 10:40

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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)
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.