Android JSON parsing using GSON (Google Search Optimization Notation)

GSON is a very help ful library to parse JSON it allow us to get all the details from the server without mentioning the name value pairs and reduce our most of the coding in android.

Lets start with the plugins :

we need add a plugins in android studio to start working with GSON. Since i have already installed so it is showing me to uninstall the same.

screen-shot-2016-11-06-at-3-13-10-pm

Add the below GSON library and Volley Library into your project and sync your project accordingly

screen-shot-2016-11-06-at-3-21-11-pm

Lets start with coding

  • Add an activity into your project
  • Creating Model to fetch data from Server im going to use this API to parse JSON : http://www.json-generator.com/api/json/get/cqWlUrLVvm?indent=2

It contains the following result :

{
"lastName": "doe",
"age": 26,
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
],
"firstName": "John",
"address": {
"postalCode": "630-0192",
"city": "Nara",
"streetAddress": "naist street"
}
}

We are going to parse above JSON by using GSON

Let add a model class and then press (COMMAND + N) In Mac and (Control+N) in Windows
as shown below

screen-shot-2016-11-06-at-3-28-01-pm

Clock on GSON Format and paste the above result which we have get from the API it will look like the below result

screen-shot-2016-11-06-at-3-30-10-pm

Click Okey, After clicking Okey this below screen appear: Again Click
okey
After clicking okey the new model code will be generated.

the generated code would be this :

package info.infiniteloops.gson;

import java.util.List;

/**
 * Created by asna on 11/6/16.
 */

public class GSONModel {

    /**
     * lastName : doe
     * age : 26
     * phoneNumbers : [{"type":"iPhone","number":"0123-4567-8888"},{"type":"home","number":"0123-4567-8910"}]
     * firstName : John
     * address : {"postalCode":"630-0192","city":"Nara","streetAddress":"naist street"}
     */

    private String lastName;
    private int age;
    private String firstName;
    /**
     * postalCode : 630-0192
     * city : Nara
     * streetAddress : naist street
     */

    private AddressBean address;
    /**
     * type : iPhone
     * number : 0123-4567-8888
     */

    private List<PhoneNumbersBean> phoneNumbers;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public AddressBean getAddress() {
        return address;
    }

    public void setAddress(AddressBean address) {
        this.address = address;
    }

    public List<PhoneNumbersBean> getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List<PhoneNumbersBean> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

    public static class AddressBean {
        private String postalCode;
        private String city;
        private String streetAddress;

        public String getPostalCode() {
            return postalCode;
        }

        public void setPostalCode(String postalCode) {
            this.postalCode = postalCode;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getStreetAddress() {
            return streetAddress;
        }

        public void setStreetAddress(String streetAddress) {
            this.streetAddress = streetAddress;
        }
    }

    public static class PhoneNumbersBean {
        private String type;
        private String number;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }
    }
}

Lets start with the implementation On activity:

Your Volley Custom Sigleton class will like this name it as:
create new class and name it as
MySigleton.java

package info.infiniteloops.gson;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}

Let see what we need add in MainClass i have named this class as GSONExamplee.java you can name whatever name you want but follow the Conventions.

Code can be written as :

package info.infiniteloops.gson;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import org.json.JSONObject;

import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Collection;

import info.infiniteloops.R;

public class GSON_Examplee extends AppCompatActivity {
    GSONModel[] gsonModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gson__examplee);
        GETJSONNDetails();
    }
    private void GETJSONNDetails(){
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.GET, "http://www.json-generator.com/api/json/get/cqWlUrLVvm?indent=2", null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Gson gson = new Gson();
                        JsonReader reader = new JsonReader(new StringReader(response.toString()));
                        reader.setLenient(true);
                        Type callDetailsCollection = new TypeToken<Collection<GSON_Examplee>>() {
                        }.getType();
                        Collection<GSONModel> enums = gson.fromJson(reader, callDetailsCollection);
                        gsonModel = enums.toArray(new GSONModel[enums.size()]);
                        System.out.println("Symbol : " + gsonModel[0].getFirstName());
                        Toast.makeText(GSON_Examplee.this,"GSON First name : "+gsonModel[0].getFirstName(),Toast.LENGTH_LONG).show();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub

                    }
                });

// Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
    }
    static ProgressDialog pDialog;

    public static void showLoadingDialog(Context mContext){
        pDialog = new ProgressDialog(mContext);
        pDialog.setCancelable(false);
        pDialog.setMessage("Loading, Please wait...");
        pDialog.show();
    }
    public static void hideLoadingDialog(){
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

 

To get the code Fork me github I love it  :