Parsing json response from google direction api - android

I'm trying to parse the JSON response from google direction api in my android program. This is the request link bellow. I'm skipping the JSON response here because its too long and simply clicking on the link will show it.
http://maps.googleapis.com/maps/api/directions/json?origin=Windsor&destination=Leamington&sensor=false&avoid=highways&mode=walking
My code for parsing the response :
try {
JSONObject responseObject = (JSONObject) new JSONTokener(responseString).nextValue();
this.responseString = responseObject.getString("status") ;
JSONArray routesArray = responseObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs ;
JSONObject leg ;
JSONArray steps ;
JSONObject dist;
Integer distance ;
if(route.has("legs")) {
legs = route.getJSONArray("legs");
leg = legs.getJSONObject(0) ;
steps = leg.getJSONArray("steps"); // EDIT : I had somehow missed this line before when copying the code from IDE to the website
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
JSONObject step = steps.getJSONObject(i);
if(step.has("distance")) {
dist = (JSONObject) step.get("distance");// throws exception
//I would like to take the distance value and do something with it
//if(dist.has("value"))
// distance = (Integer) dist.get("value") ;
}
}
}
else
this.responseString = "not found" ;
} catch ( Exception e) {
e.printStackTrace() ;
}
This throws an exception (again skipping because the JSON response is too big. The stack trace shows the entire response string) :
org.json.JSONException: Expected ':' after polyline at character 13837 of {
"routes" : [
{
"bounds" : {
"northeast" : { ....
I have tried using the getJSONObject function instead of get, but I get the same exception.
dist = step.getJSONObject("distance");
Can anyone please help me by pointing out what am I missing here ? I'm not very familiar with parsin JSON on android yet, so it's quite likely that I'm making a silly mistake somewhere. Thanks.
Another similar post on this site, but not quite the same : JSON parsing of Google Maps API in Android App

As you aren't so familiar, i'd suggest parsing JSON using Gson, esp for complex responses. The case would suit better in your case.
I have used Gson for parsing responses from Google Maps API, Places API and more...
You may be better off using Gson to parse, map data and your model classes. Eg.:
Gson gson = new Gson();
ModelClass modelClass= new ModelClass(); //or ArrayList<ModelClass>
modelClass= gson.fromJson(responseContent,ModelClass.class);
//where responseContent is your jsonString
Log.i("Web service response", ""+modelClass.toString());
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like
#SerializedName. (So no need to use Serializable)
You can use a for-each loop and verify or operate the data from the model classes.
for(Modelclass object: modelClass.getList()) {
}
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?
Also, use a for-each instead of for(;;) where ever possible.
Check these:
Parsing data with gson from google places
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse google places json
I am working on the same API right now, thought this would also help, for the model classes:
Displaying multiple routes using Directions API in Android

Try this..
steps = leg.getJSONArray("steps");
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
if(steps.has("distance")) {
JSONObject new_onj = steps.getJSONObject(i);
dist = new_onj.getJSONObject("distance");
if(dist.has("value"))
distance = (Integer) dist.get("value");
}
}

Your for loop never sets a value for step - are you missing a line
step = steps.getJSONObject(i);
at the top of your for loop?

Related

Android Multiple Level JsonObject and JsonArray Parsing with Model class

{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How should I parse JSON?

I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.

Parsing JSON response from Volley

This might be a simple question, so sorry for that. I'm trying to develop a radio app for my internet radio station. I'm using JSON format for the requests (Example JSON) to get information from my station. For example the "title" tag. I want to get this information.
My first try:
JSONObject data = response.getJSONObject("data");
songname.setText(data.getString("title"));
But the problem is that I cannot get this information. What can I do? Thanks in advance.
As your JSON do like this
JSONObject josnOBJ = new JSONObject(response);
JSONArray jArray = josnOBJ.getJSONArray("data");
JSONObject jsonData = null;
String title = null;
for (int i=0; i < jArray.length(); i++)
{
try {
jsonData = jArray.getJSONObject(i);
title= jsonData .optString("title");
} catch (JSONException e) {
// Oops
}
}
songname.setText(title);
You could use some generic JSON parsers instead of manual work. Eg: https://github.com/bajicdusko/AndroidJsonProvider
Just create model class regarding your json content. Check examples in README on github url.
Hope i could help.
You can use GSON library in case you have lot of values to fetch from JSON ,that would take care of everything for you.

Parsing JSON in Java with variable number of objects [duplicate]

This question already has answers here:
Determine whether JSON is a JSONObject or JSONArray
(9 answers)
Closed 8 years ago.
My app receives a JSON response from web services and processes the data. The response that is received could have any number of objects. My normal method of parsing is:
JSONObject jsonObj = new JSONObject(json);
JSONArray arrChanges = jsonObj.getJSONObject("Changes").getJSONArray("Row");
for (int i = 0; i < arrChanges.length(); i++)
{
// do stuff
}
This normally gets the array Row inside the object Changes, and works fine. However, I tested it with only one record being returned, and suddenly got the error: JSONObject cannot be converted to JSONArray. After looking at the json, I can see that because there is now only one object, it is no longer a JSONArray, it is now just a JSONObject. Meaning that trying to use getJSONArray will obviously fail.
So my question is; considering I will receive a varying number of items (0 to lots), how can I reliably parse this data (without knowing how many records it will have)?
Try editing parsing with the help of this concept
if (<your jsonobject> instanceof JSONArray)
{
//parse as an jsonarray
for(....;....;...){
//your logic
}
}
else{
//parse as jsonobject without using any index value
}
hope this help you with your problem.
Force your json to be an array on the client side.
EDIT: I said client, I just mean wherever you are creating it.
var json = [];
json.push({"yourdataname":"yourdatavalue"});
Just another way to do it:
try{
JSONArray arrChanges = jsonObj.getJSONObject("Changes").getJSONArray("Row");
for (int i = 0; i < arrChanges.length(); i++)
{
// do stuff
}
}catch(JSONException e){
//i assume that the actual data is json array if not this block is called try jsonobject parsing here
// its something like try catch inside try catch
}

android json response key value, parsing

i get a JSON response from a web service:
{"CoverageSearchByLatLongResult":{"HasTransmissionAreasWithSignal":true,"SwitchOffArea":
{"OpenForVastApplications":false,"SeperateTileSetUrl":"http:\/\/myswitch.merged.stage.orchard.net.au\/geodatafiles\/SwitchOffArea\/442b8844-3c05-4548-9424-
4fdafc1f3c62\/Seperate","HASStatus":"Future","HASStatement":"<p>The Household Assistance Scheme is not yet available in this switchover area. Eligible households will be sent a letter when the scheme opens in the Sydney area.<\/p>","SwitchOffDate":"31 December 2013","Events":{"MaximumProximity":6.864859435168742,"Items":[{"Name":"Test Event","Time":"Time","Url":"","Date":"Date","Address":"19a Boundary Street, Rushcutter...
so my question is, in android java how to ask for the key: CoverageSearchByLatLongResult
in ObjC in iphone , something like this:
NSDictionary *coverageResult = [response objectForKey:#"CoverageSearchByLatLongResult"];
so basically im parsing a dictionary with a key, but that result i need to put it inside other dictionary,
[correct me if wrong, in java dictionaries are called maps?]
how to do this?
thanks a lot!
You should use the classes in the org.json package:
http://developer.android.com/reference/org/json/package-summary.html
With them you can do things like:
try {
String jsonString = "YOUR JSON CONTENT";
JSONObject obj = new JSONObject(jsonString);
JSONObject anotherObj = obj.getJSONObject("CoverageSearchByLatLongResult");
boolean bool = anotherObj.getBoolean("HasTransmissionAreasWithSignal");
JSONArray jsonArray = obj.getJSONArray("arrayKey");
int i = jsonArray.getInt(0);
} catch (JSONException e) {
e.printStackTrace();
}
Java Maps map keys to values. As an example of their use:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("string key", 1);
map.put("another key", 3);

Categories

Resources