Home » Android » Android Core » Android JSON Parsing with Gson Tutorial

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He 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.

Want to create a kick-ass Android App?

Subscribe to our newsletter and download the Android UI Design mini-book right now!

With this book, you will delve into the fundamentals of Android UI design. You will understand user input, views and layouts, as well as adapters and fragments. Furthermore, you will learn how to add multimedia to an app and also leverage themes and styles!


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:

package com.javacodegeeks.android.json.model;

import java.util.List;

import com.google.gson.annotations.SerializedName;

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:

package com.javacodegeeks.android.json.model;

import com.google.gson.annotations.SerializedName;

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”:

package com.javacodegeeks.android.json.model;

import com.google.gson.annotations.SerializedName;

public class Metadata {
    public String resultType;


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

package com.javacodegeeks.android.json;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;

public class JsonParsingActivity extends Activity {
    String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    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 our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area from our partners over at ZipRecruiter



  1. You can have full JSON Parsing example using native classes: http://www.technotalkative.com/android-json-parsing/

  2. I’ve downloaded the source code and tried it but it didn’t work :(

  3. can u tell me output of this example.or show output of screen shot of android emulator.and one more question.

    i m confuse about which parsing is use json class provided by android or gson API.which one is good?

    can anybody tell me answer of the following problem?
    suppose on the client i want to access web service and consider that web service  return java object instead of json string then is it possible to parse that java object into json object and shows the result in android listview????????. if no then tell me the solution of this problem.Thanks in advanced….  

  4. There’s no need for @SerializedName(“refresh_url”) annotations all over the place.  Just use a field naming policy like this:

          gson = new GsonBuilder().

    • This is OK if the fields in the response are in English. But if they are in another language, it becomes hard to understand what exactly is what when you work with this object :)

  5. Hi ,

    I am beginner in Android, and I was able to run your sample. Thank you.

    But, In the following line of code, I was unable to understand as to how “fromJson” function is also automatically populating the  public List list, member of SearchResponse class?

    SearchResponse response = gson.fromJson(reader, SearchResponse.class);

    I mean I am unable to see any separate function that populates the list:–JC

  6. You know what, thank you very much from the bottom of my heart.

  7. What if I want to send a parameters to my webservice? 

  8. Eugène van der Merwe

    Dude you are a hero, this code really helped me.

  9. Was getting “unfortunately, … has stopped working” in jelly bean emulator until I renamed “lib” folder to “libs” then all was well : )

  10. Can i retrieve data from an executed php file on a database?

  11. Thanks my friend helped me a lot.

  12. Hi,


    Is it possible to make JSON Parser more generic ?

    Without mentioning any parent or child node tag in the code i need to parse the JSON file and display it in a Android Activity.


  13. That was a great little bit of code.. So clean I could eat off it. Respect!

  14. This was very well done and clear but how do I apply it to this data? This is not a list/array but a set of discrete values. I think I know what to do if it were a list/array

    “name”:”L’\u00c9re des Glaciers”,
    “name”:”Vieux Baie-Comeau – Le Centre Ville “,
    “name”:”La Premi\u00e8re \u00c9v\u00each\u00e9″,

  15. Found My own answer:
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    Gson gson = new Gson();
    Type cacheResultsType = new TypeToken<Map>(){}.getType() ;
    Map map = gson.fromJson(in, cacheResultsType);

  16. This is my java file:
    package com.example.backup;

    import javax.xml.transform.Result;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import com.google.gson.Gson;

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.Spinner;
    import android.widget.TextView;

    public class HomeSpinner extends Activity{
    Spinner s1,s2;
    TextView tv2,tv3;
    Button cam,vid,logout;
    ProgressBar pg;

    private final String NAMESPACE = “http://tempuri.org/”;
    private final String URL = “”;
    private final String SOAP_ACTION =”http://tempuri.org/ValidateUser”;
    // private final String METHOD_NAME =”ValidateUser”;
    private String TAG =”mani”;
    // ArrayAdapter property,product;
    SoapObject response = null;
    /*ArrayList propertyname = new ArrayList();
    ArrayList productname = new ArrayList();
    ArrayList productid = new ArrayList();*/

    private static String METHODNAME=”getpropertyhousename”;
    private static String PRODUCTMETHODNAME=”getproductdetails”;
    private static String PRODUCTINPUT=”propertyname”;
    private static String responseJSON;
    String[] propertylist;
    String[] roomlist;
    // String productName1 =””;
    // String nm;
    Gson gson = new Gson();

    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


    tv2 = (TextView)findViewById(R.id.textView2);
    tv3 = (TextView)findViewById(R.id.textView3);
    pg = (ProgressBar)findViewById(R.id.progressBar1);
    cam = (Button)findViewById(R.id.button1);
    vid = (Button)findViewById(R.id.button2);
    logout = (Button)findViewById(R.id.button3);
    s1 = (Spinner)findViewById(R.id.spinner1);
    s2 = (Spinner)findViewById(R.id.spinner2);
    AysncProperty task = new AysncProperty();

    s1.setOnItemSelectedListener(new OnItemSelectedListener() {

    public void onItemSelected(AdapterView arg0, View arg1,
    int arg2, long arg3) {
    // TODO Auto-generated method stub
    String floor = s1.getSelectedItem().toString();
    AsyncRoom task = new AsyncRoom();

    public void onNothingSelected(AdapterView arg0) {
    // TODO Auto-generated method stub


    private class AysncProperty extends AsyncTask{

    protected Result doInBackground(String… params) {
    // TODO Auto-generated method stub
    Log.i(“tag”, “doInBackground”);
    // invokeJSONWS(“Property”, “METHODNAME”);

    return null;

    protected void onPostExecute(Result result) {
    // TODO Auto-generated method stub
    Log.i(“tag”, “onPostExecute”);
    propertylist = gson.fromJson(responseJSON, String[].class);
    ArrayAdapteradapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, propertylist);

    protected void onPreExecute() {
    // TODO Auto-generated method stub
    Log.i(“tag”, “onPreExecute”);
    protected void onProgressUpdate(String… values) {
    // TODO Auto-generated method stub
    Log.i(“tag”, “onProgressUpdate”);
    public class AsyncRoom extends AsyncTask{
    protected Result doInBackground(String… params) {
    // TODO Auto-generated method stub
    Log.i(“tag”, “doInBackground”);
    invokeJSONWS(“params[0]”, “roomlist”);

    return null;
    protected void onPostExecute(Result result) {
    // TODO Auto-generated method stub
    Log.i(“tag”, “onPostExecute”);
    propertylist = gson.fromJson(responseJSON, String[].class);
    ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, roomlist);
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    Log.i(“tag”, “onPreExecute”);
    protected void onProgressUpdate(Void… values) {
    // TODO Auto-generated method stub
    Log.i(“tag”, “onProgressUpdate”);
    public void invokeJSONWS(String Property ,String methname){
    SoapObject request = new SoapObject(NAMESPACE, methname);
    PropertyInfo paramPI = new PropertyInfo();

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
    androidHttpTransport.call(SOAP_ACTION+methname, envelope);
    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
    responseJSON = response.toString();
    } catch (Exception e) {
    // TODO: handle exception

    and iam getting error in this line:
    ArrayAdapteradapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, propertylist);

  17. Hey, nice tutorial. The link in your tutorial http://search.twitter.com/search.json?q=javacodegeeks appears broken. Could you fix it?


  18. As one cat above already said, the URL to target no longer works.

    I tried this, but unfortunately the sample URL given (“http://search.twitter.com/search.json?q=javacodegeeks”) no longer works, as the Big Tweeter has pulled the rug out from under our feet and made it obsolete/deprecated it.

    Running the app simply resulted in the “The response was empty.” toast.

    Pasting the old URL directly into a browser gave me this more illuminating response:

    {“errors”:[{“message”:”The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.”,”code”:64}]}


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

  20. thank u mr Mayani
    nice topick

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

  22. can u plz help me i am getting class not found exception when i run this project. Please let me know the reason and how to fix it.

  23. This article does not work any more. I think it is outdated. You cant use network in UI thread, but you MUST create an AsyncTask for it.
    Hope this help someone else.
    This is a good thread to follow http://stackoverflow.com/questions/19551242/parsing-a-complex-json-object-using-gson-in-java .

  24. hello , i have a question, i can parse this json :

    private String strJSONValue = “{ \”Android\” :[{\”song_name\”:\”Gimme Dat\”,\”song_id\”:\”1932\”,\”artist_name\”:\”Sidney Samson (Feat. Pitbull & Akon)\”},{ \”song_name\”:\”F-k The Money (Remix)\”,\”song_id\”:\”73\”,\”artist_name\”:\”B.o.B. (Feat. Wiz Khalifa)\”}] }”;

    like this :

    String OutputData = “”;
    JSONObject jsonResponse;

    try {

    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
    jsonResponse = new JSONObject(strJSONValue);

    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
    /******* Returns null otherwise. *******/
    JSONArray jsonMainNode = jsonResponse.optJSONArray(“Android”);

    /*********** Process each JSON Node ************/

    int lengthJsonArr = jsonMainNode.length();

    for(int i=0; i < lengthJsonArr; i++)
    /****** Get Object for each JSON node.***********/
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

    /******* Fetch node values **********/
    int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());
    String song_name = jsonChildNode.optString("song_name").toString();
    String artist_name = jsonChildNode.optString("artist_name").toString();

    OutputData += "Node : \n\n "+ song_id +" | "
    + song_name +" | "
    + artist_name +" \n\n ";
    //Log.i("JSON parse", song_name);

    /************ Show Output on screen/activity **********/
    showMessage(OutputData, "STunes") ;

    } catch (JSONException e) {

    showMessage("STunes", "Error");}


    My question is how i cand parse this json :

    {"music":[{"external_ids":{"isrc":"GBAMC9800041","upc":"731453835122"},"play_offset_ms":117680,"external_metadata":{"deezer":{"album":{"id":1939301},"artists":[{"id":119}],"genres":[{"id":132}],"track":{"id":20309341}}},"title":"Whiskey In The Jar","duration_ms":"0","album":{"name":"Garage Inc."},"acrid":"01272c3cd88a9b38e268ed038989b885","genres":[{"name":"Pop"}],"artists":[{"name":"Metallica"}]}],"timestamp_utc":"2015-08-13 05:43:55"}

    I can't find an answer

  25. Very nice article and would like to share few tools for JSON lovers http://codebeautify.org/jsonviewer and http://jsonformatter.org

  26. Type listType = new TypeToken<List>(){}.getType();
    List posts = (List) gson.fromJson(response, listType);

  27. above code not working for JSON Array

  28. code not working full error

  29. pls check and then paste the code

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns