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 Tutorial

Apart from XML, JSON is a very common format used in API responses. Its simplicity has helped to gain quite the adoption in favor of the more verbose XML. Additionally, JSON can easily be combined with REST producing clear and easy to use APIs. Android includes support for JSON in its SDK as someone can find in the JSON package summary. However, using those classes, a developer has to deal with low level JSON parsing, which in my opinion is tedious and boring. For this reason, in this tutorial, I am going to show you how to perform automatic JSON parsing.For this purpose we are going to use the Google Gson library. From the official site:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Excellent, exactly what we need. Before delving into code, you might want to take a look at the Gson User Guide and bookmark the Gson API Javadocs. Let’s get started by downloading Gson, with the current version being 1.6. We need the gson-1.6.jar from the distribution.

Let’s proceed with creating an Eclipse project named “AndroidJsonProject” as follows:

Add the Gson JAR to your project’s classpath.

To illustrate how to use Gson for JSON parsing we are going to parse a JSON response from the Twitter API. Check the Twitter API Documentation for more info. We are going to use the Search API method for performing ad-hoc searches.

For example, for searching Twitter about JavaCodeGeeks and retrieving the results in JSON format, here is the corresponding URL:

This will give a one line JSON response containing all the relevant info. This one liner is quite hard to read, so a JSON editor would be quite handy. I use the Eclipse Json Editor plugin and works really well. Here is how the response looks formatted in my Eclipse IDE:

As you can see, we have a number of results and after that we have some other fields, such as “max_id”, “since_id”, “query” etc.

Thus, our main model object, named “SearchResponse” will be as follows:


import java.util.List;


public class SearchResponse {
    public List<Result> results;
    public long maxId;
    public int sinceId;
    public String refreshUrl;
    public String nextPage;
    public int resultsPerPage;
    public int page;
    public double completedIn;
    public String sinceIdStr;
    public String maxIdStr;
    public String query;

We provide the various public fields (getter/setters with private fields can also be used) and in those case that the field name does not match the JSON response, we annotate with the SerializedName annotation.

Note that we also have a list of results, with the corresponding model class being:



public class Result {
    public String fromUserIdStr;
    public String profileImageUrl;
    public String createdAt;
    public String fromUser;
    public String idStr;
    public Metadata metadata;
    public String toUserId;
    public String text;
    public long id;
    public String from_user_id;

    public String isoLanguageCode;

    public String toUserIdStr;

    public String source;

Finally, we have one more class named “Metadata”:



public class Metadata {
    public String resultType;


Let’s now see how all these get wired using Gson. Here is our Activity:


import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class JsonParsingActivity extends Activity {
    String url = "";
    public void onCreate(Bundle savedInstanceState) {
        InputStream source = retrieveStream(url);
        Gson gson = new Gson();
        Reader reader = new InputStreamReader(source);
        SearchResponse response = gson.fromJson(reader, SearchResponse.class);
        Toast.makeText(this, response.query, Toast.LENGTH_SHORT).show();
        List<Result> results = response.results;
        for (Result result : results) {
            Toast.makeText(this, result.fromUser, Toast.LENGTH_SHORT).show();
    private InputStream retrieveStream(String url) {
        DefaultHttpClient client = new DefaultHttpClient(); 
        HttpGet getRequest = new HttpGet(url);
        try {
           HttpResponse getResponse = client.execute(getRequest);
           final int statusCode = getResponse.getStatusLine().getStatusCode();
           if (statusCode != HttpStatus.SC_OK) { 
                  "Error " + statusCode + " for URL " + url); 
              return null;

           HttpEntity getResponseEntity = getResponse.getEntity();
           return getResponseEntity.getContent();
        catch (IOException e) {
           Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        return null;

First, we perform an HTTP GET request and retrieve the resource as a stream (if you need more details on this, check my previous tutorial Android Full App, Part 2: Using the HTTP API). We create a Gson instance and use it to perform the JSON parsing and retrieve our model object with all its fields populated.

Edit your Android manifest XML file and grant permissions for Internet access and then launch the Eclipse configuration. You shall see notifications of the latest Twitter users that have tweeted about JavaCodeGeeks.

That’s all guys, quick JSON parsing in Android with Gson. As always, you can download the Eclipse project created for this tutorial.

Happy mobile coding! Don’t forget to share!

Related Articles:

Related Snippets :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

25 Responses to "Android JSON Parsing with Gson Tutorial"

  1. Sakthimuthiah says:

    Thanks a lot! This site is excellent with clear example.

  2. javad says:

    thank u mr Mayani
    nice topick

  3. Sudipto says:

    Thanks for sharing this tutorial of JSON Parsing with GSon with us. This tutorial really helps me in understanding JSON.

Leave a Reply

× 3 = twenty one

Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: