Reputation: 35
I'm trying to iterate through google distance matrix response. I want to get the distance value(kms) using java. I'm just new to java.
{
"destination_addresses" : [
"Service Rd, Muneswara Nagar, Sector 6, Koramangala, Bengaluru, Karnataka 560034, India"
],
"origin_addresses" : [
"1, 16th Main Rd, BTM 2nd Stage, Kuvempu Nagar, Stage 2, BTM 2nd Stage, Bengaluru, Karnataka 560029, India"
],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "4.0 km",
"value" : 4035
},
"duration" : {
"text" : "18 mins",
"value" : 1060
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
From the above response I want to get the 'distance.text' value. How do I do that in java.
Thanks,
Upvotes: 0
Views: 710
Reputation: 83
There are several different ways of doing this. My preferred way is to create a Model class which 'models' the json response. This would be done in the following way.
public class GoogleDistanceMatrixApiResponse {
List<Rows> rows;
private List<String> destination_addresses;
private List<String> origin_addresses;
public List<String> getDestination_addresses() {
return destination_addresses;
}
public List<String> getOrigin_addresses() {
return origin_addresses;
}
public List<Rows> getRows() {
return rows;
}
static class Rows {
List<Element> elements;
public List<Element> getElements() {
return elements;
}
}
class Element {
Distance distance;
Duration duration;
public Distance getDistance() {
return distance;
}
public Duration getDuration() {
return duration;
}
}
class Distance {
String text;
String value;
public String getText() {
return text;
}
public String getValue() {
return value;
}
}
class Duration {
String text;
String value;
public String getText() {
return text;
}
public String getValue() {
return value;
}
}
This then allows you to simply deserialize the response by passing the model class to GSON. This then does all the hard work for you. (You will need to import the GSON dependency or jar into your project)
You then just simply do write the following line: (json variable being the json response)
GoogleDistanceMatrixApiResponse response = gson.fromJson(json,
GoogleDistanceMatrixApiResponse.class);
You can then get the distance by :
String distance =
response.getRows().get(0).getElements().get(0).getDistance().getText(
).replace("mi", "miles");
There are other ways of doing this, but I personally think this is the best one! Hope it helps.
Upvotes: 1
Reputation: 2239
As the question is very generic I am intending to answer the same way. There are several different ways on how you want to achieve this. Google distance matrix lets you choose between xml and JSON response. If it is a xml response you can use JAXB to convert the xml into classes and if it is a JSON you can use JACKSON to do it. After this all you have to do it read from that value in that specific class.
Upvotes: 1