2

Hello guys i'm reading a page that contain JSON objects with JAVA (Android)

Here is what the page contains :

{
   "destination_addresses" : [ "Safi, Maroc" ],
   "origin_addresses" : [ "Avenue Hassan II, Safi, Maroc" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,0 km",
                  "value" : 966
               },
               "duration" : {
                  "text" : "2 minutes",
                  "value" : 129
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

I know how to read from the page doing this

    JSONObject jArray = new JSONObject(result);
    String elements = jArray.getString("rows");

the elements string contain that :

[{"elements" : [{"distance" : {"text" : "1,0 km","value" : 966},"duration" : {"text" : "2 minutes","value" : 129},"status" : "OK"}]}]

But im trying to get the distance value which is "966"

Thx guys

Carsten Hoffmann
  • 901
  • 5
  • 14
Coldfire
  • 177
  • 4
  • 15

3 Answers3

2

You might want to take a look at this link:

How to parse JSON in Android

But for your particular problem you want to call something like:

int value = jArray.getJSONObject("rows").getJSONObject("elements").getJSONArray("distance").getInteger("value");
Community
  • 1
  • 1
TheIT
  • 11,919
  • 4
  • 64
  • 56
2

So you are trying to access an entry from the array. See Tutorials or examples. This is basic stuff: http://www.mkyong.com/java/json-simple-example-read-and-write-json/

You need to actually use a JSONArray (which subclasses JSONObject)

Carsten Hoffmann
  • 901
  • 5
  • 14
1

Try this..

JSONObject jObj = new JSONObject(result);
JSONArray rows = jObj.getJSONArray("rows");
for(int i = 0; i < rows.length; i++){
     JSONObject obj = rows.getJSONObject(i);
     JSONArray elements = jObj.getJSONArray("elements");
     for(int j = 0; j < elements.length; j++){
          JSONObject Jobj = elements.getJSONObject(j);
          JSONObject distance = Jobj.getJSONObject("distance");
          int distance_value = distance.getInteger("value");
          JSONObject duration = Jobj.getJSONObject("duration");
          int duration_value = duration.getInteger("value");
     }
}
Hariharan
  • 24,741
  • 6
  • 50
  • 54