6 Aug 2015

JSON Parsing Using Gson | gson example Android

JSON is a very common format used in API responses. JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server.

This tutorial will cover how to fetch and parse JSON from a remote server on Android. We will use GSON, a JSON parsing library developed by Google, to quickly parse the JSON into Java objects with very minimal work required.

Gson overview:

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 is an open-source project hosted at http://code.google.com/p/google-gson.

For more detail, visit Gson User guide

Let’s get started by downloading latest version of Gson .jar & add libs in your project.

Create two classes, SubjectBean and TopicBean. These will be our entity classes that model the data retrieved by the REST calls.You will notice that some fields have the @SerializedName("") annotation. This denotes that the property name does not match the field name in our JSON. If both names do match, there is no need for the annotation.



Steps 1: Create class SubjectBean
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

public class SubjectBean
{
    @SerializedName("subject")
    private String subject;

    @SerializedName("price")
    private String price;

    @SerializedName("auther")
    private String auther;

    @SerializedName("topics")
    private ArrayList<TopicBean> beanTopics;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {

        this.subject = subject;

    }

    public String getPrice() {

        return price;

    }

    public void setPrice(String price) {

        this.price = price;

    }

    public String getAuther() {

        return auther;

    }

    public void setAuther(String auther) {

        this.auther = auther;

    }

    public ArrayList<TopicBean> getBeanTopics() {

        return beanTopics;

    }

    public void setBeanTopics(ArrayList<TopicBean> beanTopics) {

        this.beanTopics = beanTopics;

    }

}

Steps 2: Create class TopicBean

 import com.google.gson.annotations.SerializedName;

public class TopicBean {


    @SerializedName("title")

    private String title;


    public TopicBean(String title) {

        this.title = title;
    }

    public String getTitle() {

        return title;

    }
    public void setTitle(String title) {

        this.title = title;

    }
}

Steps 3: Create class ServiceHandler
 import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ServiceHandler {

    public final static int GET = 1;
    public final static int POST = 2;

    static InputStreamReader inputStreamReader = null;

    public ServiceHandler() {}

    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     */
    public static  InputStreamReader makeServiceCall(String url, int method,List<NameValuePair> params)
    {
        try
        {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            if (method == POST)
            {
                HttpPost httpPost = new HttpPost(url);
                if (params != null)
                {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                try
                {
                    httpResponse = httpClient.execute(httpPost);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            else if (method == GET)
            {
                if (params != null)
                {
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            StatusLine statusLine = httpResponse.getStatusLine();
            if (statusLine.getStatusCode() == 200)
            {
                HttpEntity entity = httpResponse.getEntity();
                InputStream content = entity.getContent();
                inputStreamReader = new InputStreamReader(content);
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStreamReader;
    }
}
Steps 4: Create class MainActivity
  import android.app.ProgressDialog;

import android.os.AsyncTask;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

import com.google.gson.GsonBuilder;

import java.io.Reader;

import java.util.ArrayList;



public class MainActivity extends AppCompatActivity
{

    private ProgressDialog progressDialog;

    private SubjectBean beanSubject;

    private ArrayList<TopicBean> topicArrayList =new ArrayList<>();

    private TextView txtSubject,txtPrice,txtAuther,txtTopicsList;



    @Override

    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        txtSubject= (TextView) findViewById(R.id.txtSubject);

        txtPrice= (TextView) findViewById(R.id.txtPrice);

        txtAuther= (TextView) findViewById(R.id.txtAuther);

        txtTopicsList= (TextView) findViewById(R.id.txtTopicsList);



        new AsyncTaskData().execute();

    }



   class AsyncTaskData extends AsyncTask<Void,Void,Void>

    {

        StringBuffer topicList;

        @Override

        protected void onPreExecute()

        {

            super.onPreExecute();

            progressDialog=new ProgressDialog(MainActivity.this);

            progressDialog.setCancelable(false);

            progressDialog.setMessage("Loading...");

            progressDialog.show();

        }

        @Override

        protected Void doInBackground(Void... voids)

        {

            Reader reader= ServiceHandler.makeServiceCall("http://beta.json-generator.com/api/json/get/OkS85Le",ServiceHandler.GET,null);


            if(reader!=null)
            {

                beanSubject = new GsonBuilder().create().fromJson(reader, SubjectBean.class);



                topicArrayList=beanSubject.getBeanTopics();

                topicList=new StringBuffer();

                for(TopicBean topic: topicArrayList)
                {

                    Log.e("topic title: ",topic.getTitle()+"");
                    topicList.append("->"+topic.getTitle()+"\n");

                }

            }

            return null;

        }

        @Override

        protected void onPostExecute(Void aVoid)

        {

            super.onPostExecute(aVoid);

            progressDialog.dismiss();

            txtSubject.setText("Subject: "+beanSubject.getSubject());

            txtPrice.setText("price: "+beanSubject.getPrice());

            txtAuther.setText("Auther: "+beanSubject.getAuther());

            txtTopicsList.setText("Topics: "+"\n"+topicList);

        }

    }

}
Steps 5: Add permission to AndroidManifest.xml

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

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



I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

4 comments: