java - Parsing JSON Objects with Different Keys -


i created android application uses google books api. when json response server, parse response , retrieve title, authors, category, publisher, page count, thumbnail , more information book. problem books in json response don't have thumbnail key or category key. when try json key values program throws error , consequently skips code of adding other books after error occurred.

i solved nested try catch blocks. example, if there isn't publisher key in response, return null.

string publisher;   try {     publisher = volumeinfo.getstring("publisher");   } catch (jsonexception e) {     publisher = null;   } 

here how whole method parsing json response looks like:

private list<bookdata> parsejsonresponse(string jsonresponse) {     list<bookdata> bookdata = new arraylist<>();      try {         jsonobject rootobject = new jsonobject(jsonresponse);         jsonarray itemsarray = rootobject.getjsonarray("items");         (int = 0; < itemsarray.length(); i++) {             jsonobject itemobject = itemsarray.getjsonobject(i);             jsonobject volumeinfo =                itemobject.getjsonobject("volumeinfo");              string title;             try {                 title = volumeinfo.getstring("title");             } catch (jsonexception e) {                 title = null;             }              arraylist<string> authors;             try {                 jsonarray authorsarray =                    volumeinfo.getjsonarray("authors");                 authors = new arraylist<>();                 (int j = 0; j < authorsarray.length(); j++) {                     authors.add(authorsarray.getstring(j));                 }             } catch (jsonexception e) {                 authors = null;             }              arraylist<string> categories;             try {                 jsonarray categoriesarray =                    volumeinfo.getjsonarray("categories");                 categories = new arraylist<>();                 (int k = 0; k < categoriesarray.length(); k++) {                     categories.add(categoriesarray.getstring(k));                 }             } catch (jsonexception e) {                 categories = null;             }              string publisher;             try {                 publisher = volumeinfo.getstring("publisher");             } catch (jsonexception e) {                 publisher = null;             }              string publisheddate;             try {                 publisheddate =                    volumeinfo.getstring("publisheddate");             } catch (jsonexception e) {                 publisheddate = null;             }              int pagecount;             try {                 pagecount = volumeinfo.getint("pagecount");             } catch (jsonexception e) {                 pagecount = 0;             }              string language;             try {                 language = volumeinfo.getstring("language");             } catch (jsonexception e) {                 language = null;             }              string description;             try {                 description = volumeinfo.getstring("description");             } catch (jsonexception e) {                 description = null;             }              string bookwebsite;             try {                 bookwebsite = volumeinfo.getstring("infolink");             } catch (jsonexception e) {                 bookwebsite = null;             }              bitmap thumbnail;             try {                 jsonobject imagelink =                    volumeinfo.getjsonobject("imagelinks");                 string thumbnailurl =                    imagelink.getstring("thumbnail");                 thumbnail = getthumbnailbitmap(thumbnailurl);             } catch (jsonexception e) {                 thumbnail = null;             }              // add new bookdata object list             bookdata.add(new bookdata(title, thumbnail, authors,                         categories, publisher, publisheddate,                         pagecount, language, description,                        bookwebsite));         }     } catch (jsonexception e) {         log.e(log_tag, null, e);     }     return bookdata; } 

after complete parsing, have update views. using list view, adapter needs handle views inflation. had add if statement check if variable not null, example set text of text view. else set text "publisher not available".

textview publisher = listview.findviewbyid(r.id.book_publisher);   if (bookdata.getpublisher() != null) {     publisher.settext(bookdata.getpublisher());     } else {     publisher.settext("publisher not available");     } 

here how whole adapter looks like:

public class bookdataadapter extends arrayadapter<bookdata> {  public bookdataadapter(@nonnull context context, @nonnull                          list<bookdata> bookdatas) {     super(context, 0, bookdatas); }  @nonnull @override public view getview(int position, @nullable view convertview,                       @nonnull viewgroup parent) {     view listview = convertview;     if (listview == null) {         listview = layoutinflater.from(getcontext())                 .inflate(r.layout.book_list_item, parent, false);     }     // current bookdata object     bookdata bookdata = getitem(position);      imageview thumbnail = listview.findviewbyid(r.id.book_thumbnail);     if (bookdata.getthumbnail() != null) {         thumbnail.setimagebitmap(bookdata.getthumbnail());     } else {         // set default thumbnail         thumbnail.setimageresource(r.drawable.default_thumbnail);     }      textview title = listview.findviewbyid(r.id.book_title);     if (bookdata.gettitle() != null) {         title.settext(bookdata.gettitle());     } else {         title.settext("title not available");     }      textview author = listview.findviewbyid(r.id.book_author);     if (bookdata.getauthors() != null) {         author.settext(listtostring(bookdata.getauthors()));     } else {         author.settext("authors not available");     }      textview category = listview.findviewbyid(r.id.book_category);     if (bookdata.getcategories() != null) {         category.settext("category: " +        listtostring(bookdata.getcategories()));     } else {         category.settext("category not available ");     }      textview publisher = listview.findviewbyid(r.id.book_publisher);     if (bookdata.getpublisher() != null) {         publisher.settext(bookdata.getpublisher() + ", ");     } else {         publisher.settext("publisher not available, ");     }      textview publisheddate =        listview.findviewbyid(r.id.book_published_date);     if (bookdata.getpublisheddate() != null) {         publisheddate.settext(bookdata.getpublisheddate());     } else {         publisheddate.settext("published date not available");     }      textview pagecount = listview.findviewbyid(r.id.book_page_count);     if (bookdata.getpagecount() != 0) {         pagecount.settext("pages: " + bookdata.getpagecount());     } else {         pagecount.settext("page count not available");     }      textview language = listview.findviewbyid(r.id.book_language);     if (bookdata.getlanguage() != null) {         language.settext(bookdata.getlanguage());     } else {         language.settext("language not available");     }      textview description =        listview.findviewbyid(r.id.book_description);     if (bookdata.getdescription() != null) {         description.settext(bookdata.getdescription());     } else {         description.settext("description not available");     }     return listview; }  private string listtostring(list<string> list) {     if (list == null || list.size() == 0) {         return null;     }     stringbuilder builder = new stringbuilder();     (int = 0; < list.size(); i++) {         builder.append(list.get(i));         if (i == (list.size() - 1)) {             break;         }         builder.append(", ");     }     return builder.tostring(); } 

}

and lastly want ask question. there better way or more efficient way of parsing json response different keys, because people nested try catch statements not practice?

thank much!!

you have 2 options:

  1. using .has():

    string publisher = null; if(volumeinfo.has("publisher")){     publisher = volumeinfo.getstring("publisher"); } 
  2. using opt instead of get (better, imo):

    string publisher = volumeinfo.optstring("publisher"); 

opt### methods default null objects , 0/false primitives, don't have write try/catch blocks or if conditions. can specify second parameter default value:

string publisher = volumeinfo.optstring("publisher", "no publisher"); // if publisher not valid key, "no publisher" returned 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -