Why won't eclipse allow me to parse JSON? - android

I want to parse the JSON file at this link: http://maps.googleapis.com/maps/api/directions/json?origin=33.7489,-84.3881&destination=33.7514,-84.7478&sensor=false
I want to parse the "html_instructions" string, from the "steps" array as such:
String googledirectionsapi = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination0 + "&sensor=false";
try {
JSONObject googleObject = Directions.getJSONfromURL(googledirectionsapi);
JSONArray parsedGoogleDirections = googleObject.getJSONArray("routes").getJSONArray("steps");
thing.setText(googledirectionsapi);
if(parsedGoogleDirections.equals("") ){
Toast.makeText(FindDealer.this, "Cannot find suitable route", Toast.LENGTH_LONG).show();
}else{
for (int i = 0; i < parsedGoogleDirections.length(); i++) {
JSONObject instructions = parsedGoogleDirections.getJSONObject(i);
if (i == 0){
String step1 = parsedGoogleDirections.getString("html_instructions");
}
}
}
}catch (JSONException e) {
Log.d("log_tag","JSON parsing error - Google Directions Api:" + e.getMessage());
}
However, eclipse is giving me errors at:
.getJSONArray("steps"); //<-- The method getJSONArray(int) in the type JSONArray is not applicable for the arguments (String).
and and also giving me errors at:
.getString("html_instructions"); //<--he method getString(int) in the type JSONArray is not applicable for the arguments (String)
Why is eclipse showing these errors? I've never had this issue before. THank you in advance.

There is a similar question:JSON parsing of Google Maps API in Android App
I think you should firstly get an Object from JsonArray using index. Then you should get legs as array.Then you should get an object from leg array. then you can get steps array.
https://stackoverflow.com/a/7237305/538408

Related

JSONparsing in google books api

I am trying to get results from this google books api "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20"
The code for Json parsing is
try {
JSONObject root = new JSONObject(booksJson);
JSONArray books = root.getJSONArray("items");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
JSONObject info = book.getJSONObject("volumeInfo");
String title = info.getString("title");
JSONArray authors = info.getJSONArray("authors");
String author = authors.getString(0);
JSONObject imageLinks = info.getJSONObject("imageLinks");
String imageLink = imageLinks.getString("smallThumbnail");
Book bookObject = new Book(author,title,imageLink);
booksList.add(bookObject);
Log.d(LOG_TAG + " Index :", String.valueOf(i) + " : " + String.valueOf(books.length()));
}
} catch (JSONException e) {
}
Problem is that there are 20 results when I check in web browser and it also shows 20 results when I log books.length() in logcat but It skips some books and shows fewer results as expected. Please Help.
You got less results because in for loop when you parse the data an exception occurred and you break the for loop . The data showed which the data added to your booksList before the exception occurred .
So Debug the for loop to detect which parameter you try to parse and not found so the exception occurred
Thanks

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

JSON parsing returning a null value

I am trying to parse the response i get from the network database. I am getting only one value i.e. seller id in response. When i try to pass it in JSON Object, somehow the toast after it doesn't execute and the toast after it is not executed.
I know there are many related questions but i can't find whats wrong... please help. Thanks.
try {
JSONArray jArray = new JSONArray(stuff.toString());
Toast.makeText(this, "len: " + jArray.length(), 1000).show(); // length is 1
for (int i = 0; i < jArray.length(); i++) {
Toast.makeText(this, "Arr: " + stuff, 1000).show();
// Arr: [{"seller_id":"5"}]
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(stuff);
// not getting executed
Toast.makeText(this, "JSON: " + j_id, 1000).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this, "View: " + j_id, 1000).show(); // j_id is giving null value
This is my json data [{"seller_id":"5"}] i am trying to get the value of seller id (ie 5 here) out of it.
There is a problem in jObject.getString() method args
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(stuff);
Your giving the array. It should the name of the object i.e seller_id
so after the modification your code would be j_id = jObject.getString("seller_id");
After the following code:
j_id = jObject.getString(stuff);
add textview.settext(j_id);
and change this textview with your textview name
and if its not working than show your complete json data.

JSON Error Value free at 6 of type java.lang.String cannot be converted to JSONObject

I don't see what's wrong with my JSON, I'm getting the error that it cannot be converted to JSONObject. I searched on the forum but I can't find the answer.
Code (to parse):
JSONObject json = new JSONObject(result.toString().replace("\\", " "));
JSONArray jArray = json.getJSONArray("timetable");
for(int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String class_school = json_data.getString("class");
String teacher = json_data.getString("teacher");
String subject = json_data.getString("subject");
String room = json_data.getString("room");
timetList.add(new TimeTable(subject, class_school + " " + teacher + " " + " " + room));
}
JSON:
{"timetable":[{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},{"teacher":"Rom","subject":"FA","room":"116","change":"no"},{"teacher":"Her","subject":"GS","room":"127","change":"no"},"free","free"]}
Logcat:
03-29 15:06:11.356: E/error(822): Value free at 6 of type java.lang.String cannot be converted to JSONObject
Seems to me, you're trying to parse last two entries ("free","free") to a JSONObject. If for some reason you need to add empty entries use {}.
Consider using optString instead of getString (or use try catch statment to handle exception)
Problem is in String. Your JSON String is broken and it is reason of
Value free at 6 of type java.lang.String cannot be converted to
JSONObject
Look at your String:
{
"timetable": [
{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},
{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},
{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},
{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},
{"teacher":"Rom","subject":"FA","room":"116","change":"no"},
{"teacher":"Her","subject":"GS","room":"127","change":"no"},
"free","free"
]
}
You need to remove this unexpected sequence:
"free","free"
and last comma in JSONObject with teacher's value Her and it should work.
Your string is valid JSON; however
JSONObject json_data = jArray.getJSONObject(i);
assumes that the entity at array position i be a JSON object. "free" is a string, which is not an object type in JSON (not surrounded by {}), getJSONObject(i) throws this exception when you try to make an object out of a string.
The strings can be extracted with jArray.getString(i), but the real trick is determining the type of the entity at position i. You can try a generic jArray.get(i) and then introspect the returned value to determine its type.

Json Without Key to Parse in Android

I have this below Json which I'm getting from a .Net Web service:
[["Developer","test","developer#test.com"]]
I checked with jsonlint validator and It shows above json fine.
Because it is not having any key I don't know how to parse it in Android.
Can someone please help me how to parse this json without key.
If it had keys, I would have tried this:
{"first":"somevalue","last":"someothervalue"} // Json response
JSONObject json_obj = new JSONObject(resp); //response is the json array
String first = json_obj.getString("first");
String last = json_obj.getString("last");
String test = "Hello! " + first + " " + last;
Hope someone helps :)
Regards,
Praveen
MY SOLUTION
JSONArray respo = new JSONArray(resp); //resp is Json Array
respo = respo.getJSONArray(0);
String test = respo.getString(2);
test = "Your Email Address is " + test;
in Android (Java) parsing this line looks like:
String jsonString="[[\"Developer\",\"test\",\"developer#test.com\"]]";
try {
JSONArray jsonArray=new JSONArray(jsonString);
JSONArray jsonArray2=jsonArray.getJSONArray(0);
for (int i = 0; i < jsonArray2.length(); i++) {
String valueString=jsonArray2.getString(i);
Log.e("json", i+"="+valueString);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use JSONArray instead of JSONObject. Then use the getJSONArray() function to get the array inside the array. After that you can access all values with their index and getString().

Categories

Resources