Android Json Parsing using Gson

Introduction:

     JSON - “JavaScript Object Notation” is very well structured, light weight and easy to parse. It is the best alternative for XML. For automatic JSON parsing we are going to use Google GSON library. GSON is open source library which is used to convert JSON string data into java objects and vice versa. GSON can work with arbitrary Java objects including pre-existing objects that you do not have source-code.  

     It provides two methods fromJson()  -“ convert JSON string to java objects” and  toJson()  – “create JSON string from java objects”. In this tutorial we are going to discuss about JSON parsing for JSON Array formats using GSON Library.



Using this code:

       First we are going to learn how to parse JSON in android.

1. Sample Json

       The sample JSON data by accessing 
           http://blog.teamtreehouse.com/api/get_recent_summary/

{
"status": "ok",
"count": 12,
"count_total": 2158,
"pages": 180,
"posts": [
  {
    "id": 25898,
    "url": "http://blog.teamtreehouse.com/dont-indebted-education",
    "title": "You Don’t Need to be Indebted to Your Education",
    "date": "2016-02-17 11:14:48",
    "author": "Faye Bridge",
    "thumbnail": "http://blog.teamtreehouse.com/wp-content/uploads/2016/02/Indebt-    150x150.jpeg"
   },
   {
     "id": 25904,
     "url": "http://blog.teamtreehouse.com/html-css-still-relevant-designers-2016",
     "title": "HTML and CSS: Still Relevant for Designers in 2016",
     "date": "2016-02-16 11:20:37",
     "author": "Leon Barnard",
     "thumbnail": "http://blog.teamtreehouse.com/wp- content/uploads/2016/02/htmlandcsshot-     150x150.jpg"
    },
    {
     "id": 25921,
     "url": "http://blog.teamtreehouse.com/new-course-roundup-5",
     "title": "New Course Roundup: GitHub & Python",
     "date": "2016-02-15 08:00:57",
     "author": "Faye Bridge",
     "thumbnail": null
    },
    {
      "id": 25873,
      "url": "http://blog.teamtreehouse.com/jordan-became-industry-ready-treehouse",
      "title": "Jordan Became Industry-Ready With Treehouse",
      "date": "2016-02-10 03:00:00",
      "author": "Faye Bridge",
      "thumbnail": "http://blog.teamtreehouse.com/wp-content/uploads/2016/02/student_feature-150x150.jpg"
     }  
  ]
}

 here, 
 [ and ] - this one refer Json Array
{  and } - is refer Json Object

2. Create new project in Android Studio

MainActivity.java
package kalidoss.com.jsonparsing.Activities;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONObject;

import kalidoss.com.jsonparsing.Interfaces.AsyncTaskInterface;
import kalidoss.com.jsonparsing.Models.Models;
import kalidoss.com.jsonparsing.R;
import kalidoss.com.jsonparsing.Utils.CommonAsynTask;
import kalidoss.com.jsonparsing.Utils.Constants;
import kalidoss.com.jsonparsing.Utils.Singleton;

/** * Created by kalidoss on 13/01/16. */
public class MainActivity extends AppCompatActivity {

  Context context;
  String URL =  "http://blog.teamtreehouse.com/api/get_recent_s ummary/";

    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context=this;
        callwebservice();
    }
    // Call Json service 
    public void callwebservice() {
        CommonAsynTask getAsyncTask = new CommonAsynTask(context,URL,"", "GET", new AsyncTaskInterface() {

            @Override            
public void onTaskCompleted(JSONObject jsonObject) {
                Log.e("json ","a "+jsonObject);
                Models models = new Gson().fromJson(jsonObject.toString(), Models.class);
                // Store model values into arraylists for later use
  Singleton.getInstance().contactsList.add(models);
            }
        });
        getAsyncTask.execute();
    }
}

      I am creating CommonAsyncTask.java class  to handle all Asynchronous calls. This class is responsible of showing progress indicator in onPreExceute() method, then call serviceHelper class for making a HTTP call and getting the response in doInBackground() method. then call interface in OnPreExceute() method.

CommonAsynTask.java  
package kalidoss.com.jsonparsing.Utils;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import kalidoss.com.jsonparsing.Interfaces.AsyncTaskInterface;

/** * Created by kalidoss on 13/01/16. */
public class CommonAsynTask extends AsyncTask<String,Void,JSONObject> { 
   Activity activity;
   private ActivityIndicator pDialog;
   String url, data, methodtype;
   private AsyncTaskInterface taskCompliteListener;
   private boolean isToShowIndicator;

   public CommonAsynTask(Context context, String url, String data, String methodtype, AsyncTaskInterface taskCompliteListener) {
      this.activity = (Activity)context;
      this.url = url;
      this.data = data;
      this.methodtype = methodtype;
      this.taskCompliteListener = taskCompliteListener;
      pDialog = null;
      isToShowIndicator = true;
   }
   
   public void showIndicator(boolean isToShowIndicator) {
      this.isToShowIndicator = isToShowIndicator;
   }
   @Override   protected void onPreExecute() {
      super.onPreExecute();
      if(activity == null || activity.isFinishing()){
         return;
      }
      if (!Utilities.isOnline(activity)){
         cancel(true);
         return;
      }
      if (pDialog != null && pDialog.isShowing()) {
         pDialog.dismiss();
         pDialog = null;
      }
      else if(pDialog != null)
         pDialog = null;
      if (isToShowIndicator && pDialog == null) {
         pDialog = new ActivityIndicator(activity);
         pDialog.setCancelable(false);
         pDialog.setLoadingText("Loading....");
         pDialog.show();
      }
   }

   @Override   protected JSONObject doInBackground(String... params) {
      try {
         return new ServiceHelper(activity).doHttpUrlConnectionAction(data,url,methodtype);
      } catch (Exception e) {
         try {
            return new JSONObject("Error:"+e.getMessage());
         } catch (JSONException e1) {
         }
      }
      return null;
   }

   @Override   protected void onPostExecute(JSONObject result) {
      if(!activity.isFinishing()){
         if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
         }
      }
      if(result!=null){
         if(!TextUtils.isEmpty(result.toString()) && result.toString().contains("Error:")){  
            Toast.makeText(activity, result.toString(),Toast.LENGTH_SHORT).show();
         }
      }
      taskCompliteListener.onTaskCompleted(result);
   }
}

       This ActivityIndicator.java class is used to show progress indicator along with loading text in service loading time.

ActivityIndicator.java
package kalidoss.com.jsonparsing.Utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/** * Created by kalidoss on 13/01/16. */
public class ActivityIndicator extends Dialog {

   TextView tv;
   LinearLayout lay;
   String loadingText = "Loading...";

   public ActivityIndicator(Context context) {
      super(context);
      init(context);
   }
   
   private void init(Context context) {
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setBackgroundDrawableResource(android.R.color.transparent);
      this.lay = new LinearLayout(context);
      this.lay.setOrientation(LinearLayout.VERTICAL);
      this.lay.addView(new ProgressBar(context), new LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
      this.tv = new TextView(context);
      this.setLoadingText(loadingText);
      this.tv.setTextColor(Color.WHITE);
      this.lay.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
      this.lay.addView(tv);
      this.addContentView(lay, new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
      this.setCancelable(false);
   }

   public void setLoadingText(String loadingText) {
      this.tv.setText(loadingText);
   }
}

    This AsyncTaskInterface.java class is used to redirect interface methods values in activity.

AsyncTaskInterface.java
package kalidoss.com.jsonparsing.Interfaces;

import org.json.JSONObject;
/** * Created by kalidoss on 13/01/16. */
public abstract class AsyncTaskInterface {
   public abstract void onTaskCompleted(JSONObject jsonObject);
}

      This class used to check internet connection in android devices.

Utilities.java
package kalidoss.com.jsonparsing.Utils;

import android.content.Context;
import android.net.ConnectivityManager;

/** * Created by kalidoss on 13/01/16. */public class Utilities {

    public static boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }

}

   in this class doHttpUrlConnectionAction(String Data, String URL, String Type) method should be called in order to make a HTTP call. And the method parameters are
URL – The url to make a http call
Type– The http method either GET or POST.
Data – Any parameters you want to submit to that url. This is optional.
ServiceHelper.java 
package kalidoss.com.jsonparsing.Utils;

import android.content.Context;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/** * Created by kalidoss on 13/01/16. */
public class ServiceHelper {
   Context context;
   JSONObject jsonResultText;
   private String TAG = "RequestData";
    public static String EMPTY_STRING = "";

   // Request Type   public static String REQUEST_TYPE_POST = "POST";
   public static String REQUEST_TYPE_GET = "GET";

   // Key   public static String KEY_CONTENT_TYPE = "Content-Type";
   public static String KEY_ACCEPT = "Accept";
   public static String KEY_AUTHENTICATION = "Authorization";
   public static String KEY_ERROR = "error";

   // Value   public static String VALUE_CONTENT_TYPE = "application/json";
public ServiceHelper(Context context) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); this.context = context; } public JSONObject doHttpUrlConnectionAction(String requestData, String requestURL, String requestType) throws Exception { URL url = null; BufferedReader reader = null; StringBuilder stringBuilder; Log.e(TAG, requestData + EMPTY_STRING + requestURL); try { // create the HttpURLConnection url = new URL(requestURL.replace(" ", "%20")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (requestType.equalsIgnoreCase(REQUEST_TYPE_POST)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); } connection.setRequestMethod(requestType); connection.setReadTimeout(15 * 1000); connection.setRequestProperty(KEY_CONTENT_TYPE, VALUE_CONTENT_TYPE); connection.setRequestProperty(KEY_ACCEPT,VALUE_CONTENT_TYPE); connection.connect(); if (requestType.equalsIgnoreCase(REQUEST_TYPE_POST)) { OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream()); streamWriter.write(requestData); streamWriter.close(); } // read the output from the server reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(""); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } if(!TextUtils.isEmpty(stringBuilder.toString())){ return new JSONObject(stringBuilder.toString()); } //connection. return null; } catch (Exception e) { e.printStackTrace(); throw e; } finally { // close the reader; this can throw an exception too, so // wrap it in another try/catch block. if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } }


  We need to create model class "BeanPost" and annotate field names with the SerializedName annotation. when we add serialized name to field must match with key name from JSON.

Models.java 
package kalidoss.com.jsonparsing.Models;

import com.google.gson.annotations.SerializedName;

import java.util.List;

/** * Created by Kalidoss on 17/02/16. */
public class Models {

    @SerializedName ("status")
    public String status;
    @SerializedName ("count")
    public String count;
    @SerializedName ("count_total")
    public String count_total;
    @SerializedName ("pages")
    public String pages;
    @SerializedName ("posts")
    public List<PostModel> modelLists;
}

PostModel.java 
package kalidoss.com.jsonparsing.Models;

import com.google.gson.annotations.SerializedName;

/** * Created by Kalidoss on 17/02/16. */
public class PostModel {
    @SerializedName ("id")
    public String Id;
    @SerializedName("url")
    public String url;
    @SerializedName("title")
    public String title;
    @SerializedName("date")
    public String date;
    @SerializedName("author")
    public String author;
    @SerializedName("thumbnail")
    public String thumbnail;
}


   The Singleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.


Singleton.java 
package kalidoss.com.jsonparsing.Utils;

import java.util.ArrayList;

import kalidoss.com.jsonparsing.Models.Models;

/** * Created by Kalidoss on 17/02/16. */public class Singleton {

    private static volatile Singleton instance = null;

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                // Double check                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public ArrayList<Models> contactsList = new ArrayList<Models>();
}

   Singleton Now i am going to add GSON library to our project, first download Gson 2.2.4 library here

Add that libaray to build.gradle 


dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.1.1'
    compile files('libs/gson-2.2.4.jar')
}

      Add Create MainActivity.java Activity class and create GSON instance get data in required format.
Models models = new Gson().fromJson(jsonObject.toString(), Models.class);
Then use this model to set values in your desire options (such us RecyclerView, etc....).  Look out Recycler View in Android  for list out model values in recyclerview.

Happy Coding....
Previous
Next Post »

2 comments

Write comments
Unknown
AUTHOR
April 17, 2017 at 11:12 AM delete

I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

Reply
avatar
Unknown
AUTHOR
October 6, 2017 at 11:33 AM delete

"Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating.php jobs in hyderabad.
"

Reply
avatar