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
Related
I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.
I am trying to parse a json response in android for my android application. I am getting org.json.JSONException. The response is as shown below:
{
id: "12345"
email:"abc#gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
}
I am trying to parse the response as shown below:
if (response != null) {
try {
//JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray contacts = new JSONArray(response.toString());
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
id = c.getString("_id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
}
} catch (JSONException e) {
e.printStackTrace();
}
Can any one let me know what mistake am I doing in parsing the response. All suggestions are welcome.
Simply replace this you are using "_id" instead of "id"
id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
Change this id = c.getString("_id"); to id = c.getString("id");
in the future, you may show error in logcat when parsing like this:
catch (JSONException e) {
e.printStackTrace();
Log.e("TAG", e.getMessage());
}
There are two things I can think of , first of all you should get to know that what are [] , {} . The square brackets are arrays in json and curly demonstrate the object , so I think you are casting it wrong
1>
JSONArray contacts = new JSONArray(response.toString()); "this is culprit"
You should change it to
JSONObject. Use JSONObject in place of JSONArray
and Secondly
2> change this key id = c.getString("_id");to
id = c.getString("id");
Make sure You are getting and writing spellings of all keys right else it would generate exception.
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.
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().
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