Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Android JSON Parsing with Gson Revisited

A while ago we hosted an article about using Gson for JSON parsing with Android. The tutorial was a simple showcase of how to leverage Gson with Android.

Recently, Bill Mote from the AYDABTU Development site contacted me and informed me that he had used our sample code in one of his Android applications, namely Broadcast SMS. More specifically, he refined and improved the initial version in order to create a more robust parser.

Let’s here what he has to say about his experience.

I was in the midst of writing my first Android application and I wanted to make my app “phone home” to accomplish a few things:

1. I wanted it to display a Message Of The Day (MOTD) to inform my customers of relevant information or to simply say thank you for their support occasionally,
2. I wanted it to present a list of features available in newer releases than is currently installed by any given user and provide them a vehicle for upgrading and
3. I wanted to set a low-water mark to disable older versions of the application.

A JSON web service seemed like the natural solution for this, but as I mentioned above, “I was writing my FIRST Android app.” ;)

I stumbled upon your Android JSON parsing with GSON article. What a wonderful and timely find! I know the article was simply intended to get the user started. Almost all articles are written this way. I want to give something back so I’ve taken your original article and expounded on it by hardening the HTTP request and the actual parsing of the JSON. I’ve also made the entire thing run in an AsyncTask (background thread) to get it off the UI thread as any kind of network hiccup or a large JSON string could cause the UI to become unresponsive and generate an error.

The full-on Try/Catch code can be found here: JSON Parsing Full Try-Catch.

Improvements:

* Runs as an AsyncTask to get it off the UI thread
* Handles socket/network timeouts
* Handles 404 errors
* Handles JSON syntax errors

Of note:

  • Anything that can throw an exception has been surrounded by a try/catch block and the application has been built to handle a null return.
  • I implemented an onStop() method to cancel the AsyncTask if the application should terminate as creating more than 1 AsyncTask will cause a force close.
  • Notice that we check for ‘this.isCancelled()’ before we finish the doInBackground() method — You can force this by starting the application and hitting the back button quickly.
  • You could grab the appropriate failure (aka catch()) and make the application retry on some period but that’s outside the scope of this example.

So, after making this run in a background thread and creating all those layers of try/catch complexity it occurred to me that I don’t care why it failed. I just need to account for it. I talked this over with a friend of mine that has much more development experience and he agreed with my basic idea: wrap the basic functions with a try/catch block and account for it, but remove all the layers. That includes removing the HTTP status response because in this case we don’t care if it failed. We’re either going to see the list of names or we’re not.

The simplified try-catch version of this code works in exactly the same way, but it’s less smart about why it had a problem. It can be found here: JSON Parsing Simplified Try-Catch.

My app, Broadcast SMS, has benefited from numerous on-line examples and tutorials. JavaCodeGeeks article helped me implement a JSON string parser that is working perfectly. Many thanks to them and all those that publish their works for the masses. I hope you find my enhancements useful.

Very nice, the enhancements helped create a more robust and less error-prone application. Thank you Bill. If you also have any improvements or additions you would like to contribute, please let shoot us an e-mail. Cheers!

Related Articles :
Related Whitepaper:

Rapid Android Development: Build Rich, Sensor-Based Applications with Processing

Create mobile apps for Android phones and tablets faster and more easily than you ever imagined

Use 'Processing', the free, award-winning, graphics-savvy language and development environment, to work with the touchscreens, hardware sensors, cameras, network transceivers, and other devices and software in the latest Android phones and tablets.

Get it Now!  

2 Responses to "Android JSON Parsing with Gson Revisited"

  1. I can’t seem to get this working.  There seems to also be a new button that’s been introduced. Can I get a link to the full eclipse project? It would really clear things up!

  2. Michael Weber says:

    Great improvement! But it can be implemented more generally. Basically its just important whether there is a JSONObject or a JSONArray to deserialze. So I could create a general JSONHelper including this two methods:

    private Collection deserializeJSONArray(InputStream source,
    Collection results) {
    Reader reader = new InputStreamReader(source);
    try {
    Type tokenType = new TypeToken<Collection>() {
    }.getType();
    Collection response = this.gson.fromJson(reader, tokenType);
    results.addAll(response);
    } catch (JsonSyntaxException e) {
    Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e);
    } catch (JsonIOException e) {
    Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e);
    } finally {
    try {
    reader.close();
    return results;
    } catch (IOException e) {
    Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e);
    }
    }
    return Collections.emptyList();
    }

    private T deserializeJSONObject(InputStream source, T result) {
    Reader reader = new InputStreamReader(source);
    try {
    Type tokenType = new TypeToken() {
    }.getType();
    result = this.gson.fromJson(reader, tokenType);
    } catch (JsonSyntaxException e) {
    Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e);
    } catch (JsonIOException e) {
    Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e);
    } finally {
    try {
    reader.close();
    return result;
    } catch (IOException e) {
    Log.v(Constants.LOGTAG, JSONUtil.CLASSNAME, e);
    }
    }
    return null;
    }

    Hope it helps!

    Regards,

    Michael

Leave a Reply


9 + four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books