Parsing JSON from the google maps DistanceMatrix api in android - java

I am new to android development and new to JSON. I am using the google maps distance matrix api. I have the JSON download into a JSONObject properly I believe.(I stole the code to do it from another post). However I can not seem to parse the JSON properly. I have been working at this for a few day and am completely stumped. I make the following call to google below
https://maps.googleapis.com/maps/api/distancematrix/json?origins=1600%20pennsylvania%20avenue&destinations=1500%20college%20street&mode=driving&units=imperial
The output is this:
{
"destination_addresses" : [ "1500 College Street, Beaumont, TX 77701, USA" ],
"origin_addresses" : [ "1600 Pennsylvania Avenue, Hagerstown, MD 21742, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,306 mi",
"value" : 2102536
},
"duration" : {
"text" : "18 hours 48 mins",
"value" : 67684
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I have tried:
1.
JSONArray jsonArray = jObject.getJSONArray("rows");
JSONArray routes = jsonArray.getJSONArray(0);
stringBuilder.append(routes.getJSONObject(0).getString("text"));
2.
JSONArray jsonArray = jObject.getJSONArray("rows");
JSONObject routes = jsonArray.getJSONObject(0);
stringBuilder.append(routes.getJSONObject("distance").getString("text"));
3.
JSONArray jsonArray = jObject.getJSONArray("elements"); stringBuilder.append(routes.getJSONObject(0).getString("text"));
I have tried more but those seem to me like they should work. It seemed that to me rows is an array and elements is an array as well. So it would follow that I would need to get rows out of the original JSONObject then get the element array out of the row array then get the distance object out of that array, then finally get the text value and add it to the string builder I created earlier.
Were did I go wrong? thank you in advance for any help.

Here is what worked with me
//httpResponse is the output of google api
JSONObject jsonRespRouteDistance = new JSONObject(httpResponse)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray ("elements")
.getJSONObject(0)
.getJSONObject("distance");
String distance = jsonRespRouteDistance.get("text").toString();
/*
* For distance, below is only partial solution as the
* output to string destination_addr will contain square brackets [] and double codes ""
* Eg. [ "1600 Pennsylvania Avenue, Hagerstown, MD 21742, USA" ]
*
*/
String destination_addr = new JSONObject(httpResponse)
.get("destination_addresses")
.toString();
[UPDATE]
Assuming we have only one destination address and not multiple. A little string manipulation gets us the clean string string without codes " and brackets []
StringBuilder stringBuilderDestinationAddr = new StringBuilder();
for (int i = 0; i < destination_addr.length(); i++)
if (destination_addr.charAt(i) != '[' && destination_addr.charAt(i) != ']' && destination_addr.charAt(i) != '"')
stringBuilderDestinationAddr.append(pickup_addr.destination_addr (i));
String strCleanDestination = stringBuilderDestinationAddr.toString();

Related

Accessing elements in JSON array

I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.
I'd like to pull the number 14147 from duration.
{
"destination_addresses" : [ "Washington, DC, USA" ],
"origin_addresses" : [ "New York, NY, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "226 mi",
"value" : 364089
},
"duration" : {
"text" : "3 hours 56 mins",
"value" : 14147
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I've tried a few different things, here's what I tried last (data is just the array above):
String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");
Here's the console output:
org.json.JSONException: JSONObject["duration"] not found
I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.
I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value. Thank you in advance!
First of all, please have a look at this answer. Using org.json you can do smth. like that:
JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
for(int j = 0; j < elements.length(); j++) {
JSONObject element = elements.getJSONObject(j);
JSONObject duration = element.getJSONObject("duration");
int value = duration.getInt("value");
}
}
The code above has produced following output using your json String: 14147
P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.

Parse a complex JSON result

I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}
You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");
Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.
Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");

How to access elements in java subarray without key but with index

I have an JSON that looks like this:
{ "Message": "None", "PDFS": [
[
"test.pdf",
"localhost/",
"777"
],
[
"retest.pdf",
"localhost\",
"666"
] ], "Success": true }
I'm trying to access the individual strings within the arrays but I'm having difficulty doing it as getString is requiring me to use a key and not indexes.
I've tried this to access the first string in each sub-array:
JSONArray pdfArray = resultJson.getJSONArray("PDFS");
for (int i = 0; i < pdfArray.length(); i++) {
JSONObject pdfObject = pdfArray.getJSONObject(i);
String fileName = pdfObject.getString(0);
}
Read the array as an array:
JSONArray array = pdfArray.getJSONArray(i);
String fileName = array.getString(0);

How to parse the Object in JSON type

I have a JSON file and I do not know how can I parse the part of "coordinates", others done already. It seems null, others seem ok when I try to reach them. I guess, coordinates part is another class defined in cities part. Could you please help me to get coordinates of cities?
I kept my cities in a linkedlist.
"cities" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
}
static List<City> allCities = new LinkedList<City>();
static List<Flight> allFlights = new LinkedList<Flight>();
static JSONArray cities;
static JSONArray flights;
FileReader reader = new FileReader("csair.json");
JSONObject CSAirData = (JSONObject) JSONValue.parse(reader);
cities = (JSONArray) CSAirData.get("cities");
flights = (JSONArray) CSAirData.get("routes");
Assuming "cities" is an attribute of variable myVar, like this
var myVar = {
"cities": [
{
"code": "SCL",
"name": "Santiago",
...
}
]
};
then you could access "coordinates" by doing
myVar.cities[0].coordinates
"cities" corresponds to an array
the first element in the array (index = 0) is an object
that object has an attribute called "coordinates", which references another object
Edit
Now that I see you are using Java code, you just need to transform this syntax into Java.
We know that "cities" is a JSONArray.
JSONObject city = cities.get(0); // Get the first city in the array (index = 0)
JSONObject coordinates = city.getJSONObject("coordinates");
int coordinates_s = coordinates.getInt("S");
int coordinates_w = coordinates.getInt("W");

Converting Nested Json files to CSV in java

{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}

Categories