Accessing elements in JSON array - java

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.

Related

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

Parsing JSON from the google maps DistanceMatrix api in android

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

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

Parsing JSON data in Java for Android

I hope someone might be able to help me.
I am trying to parse following json file:
{"seminar":[
{"categoryid": "1","cpe": "13","inventory":["Discussion","Value x","Value y"
],"teachers": [
{
"titel": "Dipl.-Ing.",
"company": "XY",
"name": "Test",
"id": "3",
}
],
},...
I am lost with parsing the teachers data in...
...
private static final String TAG_teachers = "teachers";
private static final String TAG_TITLE = "title";
for(int i = 0; i < seminar.length(); i++){
JSONObject c = seminar.getJSONObject(i);
...
teachers = c.getJSONArray(TAG_DOZENTEN);
for(int z = 0; z < teachers.length(); z++){
JSONObject d = teachers.getJSONObject(z);
String title = d.getString(TAG_TITLE);
Log.d("JSONParsingActivity", title);
I get the error System.err(1010): org.json.JSONException: Value null
at teachers of type org.json.JSONObject$1 cannot be converted to
JSONArray.
What did I do wrong? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. Is somebody able to help me?
You have an extra (trailing) comma in teachers (after "3"). Not allowed in JSON. Remove it and see if that helps.
If your JSON is really of the form:
{ ... }, { ... }, { ... }, ...
This is invalid JSON
The root enclosure must either be a single object (in {}) or an array (in []).
If your intent is to send an array of objects, then simply wrap the entire thing with square brackets to make it an array and create a JSONArray object from it.
So it must be like this
[ { ... }, { ... }, { ... }, ... ]
You also need to make sure that you don;t have extra commas, unclosed brackets, etc. Use JSONLint or other similar JSON format checker to save yourself some time in finding syntax problems.

Check if a particular JSON Object is available or not

I have JSON File as below which has to be dumped into an ArrayList:
{
"main1" : [
{
"child1" : valueA,
"child2" : valueB,
"child3" : valueC,
},
{
"child1" : value1,
"child3" : value3,
},
],
"main2" : "valueMain2"
}
The element child2 has to be checked if it exists or not and then the value is taken. You can see that it doesn't appear in the second array.
I am using Native JSON (org.JSON)
Java Code is below:
ArrayList<HashMap<String,String>> myList = new ArrayList<HashMap<String,String>>();
JSONObject json = <my_json_object>;
JSONObject getchild2;
JSONArray jArray = <my_json_object>.getJSONArray("main1");
for(int j = 0; j < jArray.length(), j++){
HashMap<String,String> map = new HashMap<String,String>();
map.put("First Value", jArray.getJSONObject(j).getString("child1"));
map.put("Third Value", jArray.getJSONObject(j).getString("child3"));
getchild2 = jArray.getJSONObject(j).getJSONObject("child2");
if(getchild2 == null){
map.put("Second Value", "Some Dummy Value");
} else {
map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
}
myList.add(map);
}
How can I achieve this?
<my_json_object> uses native URL Parsing as I get the HTTP Response of a URL request found here: http://mobisys.in/blog/2012/01/parsing-json-from-url-in-android/
It doesn't work as error is below:
E/AndroidRuntime(664): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Anyway, I got the solution with some Googling:
I re-framed it as,
if (!jArray.getJSONObject(j).has("child2")) {
map.put("Second Value", "N.A");
} else {
map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
}
Creating the JSONObject getchild2 = jArray.getJSONObject(j).getJSONObject("child2"); was rather, unnecessary.
And this works, rather perfectly! Refer this for more details: Checking if exists subObject in JSON
Thanks everyone for the help!
getJSONObject("child2");
Will throw an exception if child2 does not exist. Try this instead:
getchild2 = jArray.getJSONObject(j).optJSONObject("child2");
That way you don't have to catch an exception if child2 doesn't exist and can instead check for null.
Try this:
{"main1" : [{
"id":"1"
"child1" : "valueA",
"child2" : "valueB",
"child3" : "valueC",
}, {
"id":"2"
"child1" : "value1",
"child3" : "value3",
}]
}

Categories