function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AKS018AKS018 

Google Api Distance calculation problem

Hi,

          I have a problem with Json parsing and getting a particular value.Please help me how to get. First time I am working on this Json in salesforce.

 

In my controller I wrote a code like this

 

 

string url='http://maps.googleapis.com/maps/api/distancematrix/json?origins='+EncodingUtil.urlEncode(add1,'UTF-8')+'&destinations='+EncodingUtil.urlEncode(add2,'UTF-8')+'&mode=driving&language=en&sensor=false&units=imperial';
Http h = new Http();
HttpRequest req = new HttpRequest();

req.setHeader('Content-type', 'application/x-www-form-urlencoded');
req.setHeader('Content-length', '0');
req.setEndpoint(url);
req.setMethod('POST');

HttpResponse res = h.send(req);
String responseBody = res.getBody();

JSONParser parser =System.JSON.createParser(responseBody);

 

// Here I am unable to parse and get the values using Json.
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'text')) {
System.debug('##########'+parser.getText());
parser.nextToken();

}
}

 

=============================================

In Response Body I am getting the Output of Json Like

 

{
"destination_addresses" : [ "Vijayawada, Andhra Pradesh, India" ],
"origin_addresses" : [ "Hyderabad, Andhra Pradesh, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "173 mi",
"value" : 278118
},
"duration" : {
"text" : "4 hours 33 mins",
"value" : 16386
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}

 

 

From the above I have to get the Distance --Text value i.e '173 mi'

 

How to get the Distance value.Can any one Guide me please.

Best Answer chosen by Admin (Salesforce Developers) 
Mohith Kumar ShrivastavaMohith Kumar Shrivastava

http://cloudyworlds.blogspot.in/2012/12/json-to-apex-convesion-simpler-now-with.html

 

Just giving you the blog link where i demonstrated use of JSON to APEX app.

 

Oce you input your JSON you can convert to apex class and then you can use JSON.deserialise() to parse the JSON to apex class and then its very easy to get the value .

 

Try JSON.deserialise instead of explicit parsing

All Answers

Mohith Kumar ShrivastavaMohith Kumar Shrivastava

http://cloudyworlds.blogspot.in/2012/12/json-to-apex-convesion-simpler-now-with.html

 

Just giving you the blog link where i demonstrated use of JSON to APEX app.

 

Oce you input your JSON you can convert to apex class and then you can use JSON.deserialise() to parse the JSON to apex class and then its very easy to get the value .

 

Try JSON.deserialise instead of explicit parsing

This was selected as the best answer
AKS018AKS018

Thank  alot mohit.