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

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.