Getting String from Google- Books-Api when String isn't present in all Array element [duplicate]
Getting String from Google- Books-Api when String isn't present in all Array element [duplicate]
This question already has an answer here:
I am using the google books api (https://www.googleapis.com/books/v1/volumes) to query for books. I encountered an issue when trying to get the JSONObject of certain fields: eg. some values does not have a "subtitle" String in the "volumeInfo" JSONObject. This is a part of a result for 2 books
"kind": "books#volume",
"id": "XMrZrA1vomQC",
"etag": "54+ok3hELTA",
"selfLink": "https://www.googleapis.com/books/v1/volumes/XMrZrA1vomQC",
"volumeInfo":
"title": "Shakespeare",
"subtitle": "For All Time",
"authors": [
"Stanley W. Wells"
],
"publisher": "Oxford University Press on Demand",
"publishedDate": "2003-01"
,
"kind": "books#volume",
"id": "LpZRnseuZHIC",
"etag": "QxfQuF7p2Mg",
"selfLink": "https://www.googleapis.com/books/v1/volumes/LpZRnseuZHIC",
"volumeInfo":
"title": "Shakespeare, Contemporary Critical Approaches",
"authors": [
"Harry Raphael Garvin",
"Michael Payne"
],
"publisher": "Bucknell University Press",
"publishedDate": "1980"
How do I get the String for "subtitle" without encountering an error when it doesn't exist. I'm using this
String subTitle = volumeInfoObject.getString("subtitle");
but then, when it iterates to a set that doesn't have "subtitle" i receive this error in my logcat and my UI is not updated with the result
W/System.err: org.json.JSONException: No value for subtitle
How do I handle this exception? Thanks a lot
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
has()
optString()
getString()
You could check if they key exists first using
has()
, before trying to get its value. Alternatively, you could useoptString()
instead ofgetString()
, as it won't throw an Exception. Examples of both are shown in the linked duplicate.– Mike M.
2 days ago