ZOFTINO.COM android and web dev tutorials

Handling JSON Using Gson in Android

The most widely used data interchange format for exchanging data between android app and app services on server is JSON format. So it is very important for android app developers to learn how to parse JSON string into java objects and how to create JSON string from java objects.

Android SDK includes org json library using which you can parse JSON strings in android.

In this post, I am going to show how to use gson for converting between java objects and JSON string.

With gson, you can convert json string into desired java objects. Whereas with JSONObject, you have to create objects manually by getting data from JSONObject and setting it to java object you want to create.

JSON Example

To show how to use gson to convert between object and json string, we will use below json string.

{
  "coupons": [
    {
      "store": "ebay",
      "coupon": "Get upto 20% off on hand bags",
      "expiryDate": "10/10/2016",
      "couponCode": "ER4",
      "category": "fashion"
    },
    {
      "store": "amazon",
      "coupon": "Get upto 5% off on mobile phones",
      "expiryDate": "11/11/2016",
      "couponCode": "TRG4",
      "category": "electronics"
    },
    {
      "store": "etsy",
      "coupon": "Get upto 25% off on jeans",
      "expiryDate": "09/09/2016",
      "couponCode": "ERT4",
      "category": "fashion"
    },
    {
      "store": "bestbuy",
      "coupon": "Get upto 30% off on televisions",
      "expiryDate": "20/11/2016",
      "couponCode": "343",
      "category": "electronics"
    },
    {
      "store": "sears",
      "coupon": "Get upto 50% off on home and kitchen",
      "expiryDate": "11/10/2016",
      "couponCode": "ER3",
      "category": "home"
    },
    {
      "store": "walmart",
      "coupon": "Get upto 10% off on baby products",
      "expiryDate": "17/09/2016",
      "couponCode": "we33",
      "category": "baby"
    },
    {
      "store": "kohls",
      "coupon": "Get upto 22% off on kids fashion",
      "expiryDate": "",
      "couponCode": "err4",
      "category": "kids fashion"
    },
    {
      "store": "macys",
      "coupon": "Get upto 19% off on fashion",
      "expiryDate": "10/12/2016",
      "couponCode": "DSF3",
      "category": "fashion"
    },
    {
      "store": "jcpenney",
      "coupon": "Get upto 10% off on bedsheets",
      "expiryDate": "11/12/2016",
      "couponCode": "wew",
      "category": "home"
    },
    {
      "store": "wayfair",
      "coupon": "Get 5% off on everything",
      "expiryDate": "02/10/2016",
      "couponCode": "233",
      "category": "all"
    }
  ]
}

Gson Library

To use gson, you need to add gson library to your android project. You can do so, by adding below dependency to your module’s gradle build property file.

 dependencies {compile 'com.google.code.gson:gson:2.8.0'}

GSON Deserialization

Deserialization in this context is the process of converting json sting to java objects. To convert json string to java objects, you need to use fromJson method of Gson object. Method fromJson takes two parameters, one is JSON input and other one is type of root object, which is what gets populated with data from json string and returned by this method.

GSON Deserialization Example

Let’s take simple json which is an array of strings. To convert this json string to ArrayList<String> type, we need to define type and pass it to fromJson method like shown below.

["fashion","electronics","appliances","home"]
 String jsonstr = "[\"fashion\",\"electronics\",\"appliances\",\"home\"]";
final Gson gson = new Gson();

Type category = new TypeToken<List<String>>(){}.getType();

List<String> str = gson.fromJson(jsonstr, category);

GSON Serialization

Serialization in this context is the process of converting java objects into json string. It can be done using toJson method of Gson object. Method toJson takes root object as parameter and returns json string.

Below line of code converts list of strings into json string.

String json = gson.toJson(strList);

Android GSON Example

To show how to use gson in android, we’ll take from coupons app a screen which shows list of coupons.

This example uses HttpURLConnection to call rest service which responds with list of coupons in json format. It is a best practice to run this server call and parsing of json in a separate thread. So, AsyncTask is used to run the entire process in the background.

Using gson library, json response from the service call will be converted to list of coupon objects and supplied to recycler view to display it on the screen. We used recycler view item decoration to separate items by drawing divider.

Required Permissions to Run Gson Example

Add Internet Permission as this example calls rest service to get JSON response.


<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Android GSON Example Output

android json gson parsing example

Android GSON Example Code

Modal Coupon

package com.zoftino.androidui;

public class Coupon {
    private String store;
    private String coupon;
    private String expiryDate;
    private String couponCode;

    public String getStore() {
        return store;
    }

    public void setStore(String store) {
        this.store = store;
    }

    public String getCoupon() {
        return coupon;
    }

    public void setCoupon(String coupon) {
        this.coupon = coupon;
    }

    public String getExpiryDate() {
        return expiryDate;
    }

    public void setExpiryDate(String expiryDate) {
        this.expiryDate = expiryDate;
    }

    public String getCouponCode() {
        return couponCode;
    }

    public void setCouponCode(String couponCode) {
        this.couponCode = couponCode;
    }

}

Coupon Wrapper

package com.zoftino.androidui;

import java.util.List;

public class CouponsWrapper {
    private List<Coupon> coupons;

    public List<Coupon> getCouponList() {
        return coupons;
    }

    public void setCouponList(List<Coupon> couponList) {
        this.coupons = couponList;
    }
}

Activity Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.zoftino.androidui.ActivityGsonJsonParsing">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/coupons_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</LinearLayout>

RecyclerView Item Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/amazon"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"></ImageView>

    <TextView
        android:id="@+id/coupon_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toRightOf="@+id/imageView"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></TextView>

    <TextView
        android:id="@+id/coupon_expiry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/coupon_txt"
        app:layout_constraintLeft_toRightOf="@+id/imageView"
        android:layout_marginLeft="8dp"></TextView>

    <TextView
        android:id="@+id/coupon_code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@+id/coupon_expiry"></TextView>
</android.support.constraint.ConstraintLayout>

Activity

package com.zoftino.androidui;


import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class ActivityGsonJsonParsing extends AppCompatActivity {

    private String TAG = ActivityGsonJsonParsing.class.getSimpleName();

    private RecyclerView rv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gson);
        Log.d(TAG, "content view is set in onCreate method of activity");

        rv = (RecyclerView) findViewById(R.id.coupons_rv);

        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);

        LinearDividerItemDecoration lddecoration = new LinearDividerItemDecoration(this, Color.BLUE, 10);
        rv.addItemDecoration(lddecoration);

        new ActivityGsonJsonParsing.GetCouponsAync().execute(this);
    }

    private class GetCouponsAync extends AsyncTask<Context, Void, List<Coupon>> {

        private String TAG = GetCouponsAync.class.getSimpleName();
        private Context contx;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<Coupon> doInBackground(Context... params) {
            contx = params[0];
            Log.e(TAG, "start aynctask to get coupons");
            return getCouponsFromServer();
        }

        @Override
        protected void onPostExecute(List<Coupon> result) {
            super.onPostExecute(result);

            if(result != null){
                Log.e(TAG, "populate UI recycler view with gson converted data");

                CouponsRecyclerViewAdapter couponsRecyclerViewAdapter = new CouponsRecyclerViewAdapter(result,contx);
                rv.setAdapter(couponsRecyclerViewAdapter);
            }
        }
    }

    public List<Coupon> getCouponsFromServer() {
        String serviceUrl = "http://www.zoftino.com/api/coupons";
        URL url = null;
        try {
            Log.d(TAG, "call rest service to get json response");
            url = new URL(serviceUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setConnectTimeout(4000);
            connection.setReadTimeout(4000);
            connection.connect();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //pass buffered reader to convert json to java object using gson
            return convertJsonToObject(bufferedReader);

        } catch (Exception e) {
            Log.e(TAG, "error in getting and parsing response");
        }
        return null;
    }

    public List<Coupon> convertJsonToObject(BufferedReader bufferedReader){
        //instantiate Gson
        final Gson gson = new Gson();

        //pass root element type to fromJson method along with input stream
        CouponsWrapper couponsWrapper= gson.fromJson(bufferedReader, CouponsWrapper.class);

        List<Coupon> cpnlst = couponsWrapper.getCouponList();
        Log.e(TAG, "number of coupons from json response after gson parsing"+cpnlst.size());

        return cpnlst;
    }
}

RecyclerView Adapter

 package com.zoftino.androidui;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class CouponsRecyclerViewAdapter extends RecyclerView.Adapter<CouponsRecyclerViewAdapter.ViewHolder> {

    private List<Coupon> couponsList;
    private Context context;

    public CouponsRecyclerViewAdapter(List<Coupon> cLst, Context ctx) {
        couponsList = cLst;
        context = ctx;
    }

    @Override
    public CouponsRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gson_item, parent, false);

        CouponsRecyclerViewAdapter.ViewHolder viewHolder = new CouponsRecyclerViewAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CouponsRecyclerViewAdapter.ViewHolder holder, int position) {
        Coupon coupon = couponsList.get(position);
        holder.couponTv.setText(coupon.getCoupon());
        holder.expiryDateTv.setText(coupon.getExpiryDate());
        holder.couponCodeTv.setText(coupon.getCouponCode());

        //images are stored in drawable resources folder, using store name get image id
        int id = context.getResources().getIdentifier(coupon.getStore(), "drawable", context.getPackageName());
        holder.storeImg.setImageResource(id);
    }

    @Override
    public int getItemCount() {
        return couponsList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView couponTv;
        public TextView expiryDateTv;
        public TextView couponCodeTv;
        public ImageView storeImg;

        public ViewHolder(View view) {
            super(view);
            couponTv = (TextView) view.findViewById(R.id.coupon_txt);
            expiryDateTv = (TextView) view.findViewById(R.id.coupon_expiry);
            couponCodeTv = (TextView) view.findViewById(R.id.coupon_code);
            storeImg = (ImageView) view.findViewById(R.id.imageView);

            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Toast.makeText(context, "You clicked coupons at  "+ getAdapterPosition(),
                    Toast.LENGTH_LONG).show();
        }
    }
}