Home > other >  JSONObject - how can I get a value from the response?
JSONObject - how can I get a value from the response?

Time:08-31

I have a response which contains values which I need.

private void getDataFromDistanceMatrixToSaveAndAddToList(
       GRATestDataImport place, String response) {

    JSONObject responseAsJson = new JSONObject(response).getJSONArray("rows")
                                                        .getJSONObject(0)
                                                        .getJSONArray("elements")
                                                        .getJSONObject(0); 
}

'response' in params includes:

{
  "destination": [
    "54.375,18.59"
  ],
  "origin": [
    "54.001,21.721"
  ],
  "rows": [
    {
      "elements": [
        {
          "distance": {
            "text": "304.4 km",
            "value": 304403
          },
          "duration": {
            "text": "3 h 53 min",
            "value": 14003
          },
          "status": "OK"
        }
      ]
    }
  ],
  "status": "OK"
} 

value: 'responseAsJson' in my method is:

{
  "duration": {
    "text": "3 h 53 min",
    "value": 14003
  },
  "distance": {
    "text": "304.4 km",
    "value": 304403
  },
  "status": "OK"
}

How can I get value from the duration and the distance ?

CodePudding user response:

you'll just have to navigate along

int duration = responseAsJson.getJSONObject("duration").getInt("value");
int distance = responseAsJson.getJSONObject("distance").getInt("value");

CodePudding user response:

public class YourResponse
        {
        public string duration { get; set; }
        public string distance {get ;set;}
        }
         YourResponse response = JsonSerializer.Deserialize<YourResponse>(result);
  • Related