Sunday, 22 April 2012

Common JSON parser class for all type of JSON response using GSON

Hello guys, Today I am posting a class for parse all types of JSON response using a one common class.



public class HTTPPostGetData {



 Boolean isNetError=false;



 public Boolean getIsNetError() {

  return isNetError;

 }



 public void setIsNetError(Boolean isNetError) {

  this.isNetError = isNetError;

 }



 public Object getFilledObject(String url, List<NameValuePair> mNameValuePair, Object mObject, Context mContext)

 {

  String data="";

  Object mFilledObject = new Object();

  DefaultHttpClient client;

  HttpPost mHttpPost;

  HttpEntity getResponseEntity;

  HttpResponse getResponse;

  HttpParams mHttpParams;

  setIsNetError(false);

  if(checkInternetConnection(mContext))

  {

   try {

    client = new DefaultHttpClient();

    mHttpParams= client.getParams();

    HttpConnectionParams.setConnectionTimeout(mHttpParams, 30000);

    mHttpPost = new HttpPost(url);

    mHttpPost.addHeader("Accept", "application/json,text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

    mHttpPost.addHeader("Content-Type", "application/json");

    mHttpPost.setEntity(new UrlEncodedFormEntity(mNameValuePair));

    getResponse = client.execute(mHttpPost);

    final int statusCode = getResponse.getStatusLine().getStatusCode();



    if (statusCode != HttpStatus.SC_OK) {

     Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);

     setIsNetError(true);

     return mFilledObject;

    }

    try {

     mFilledObject= mObject.getClass().newInstance();

    } catch (IllegalAccessException e) {

     // TODO Auto-generated catch block

     e.printStackTrace();

    } catch (InstantiationException e) {

     // TODO Auto-generated catch block

     e.printStackTrace();

    }



    getResponseEntity = getResponse.getEntity();

    data=EntityUtils.toString(getResponseEntity);

    System.out.println("gotResponse :"+data);

    Gson mGson= new Gson();

    mFilledObject= mGson.fromJson(data, mFilledObject.getClass());



    return mFilledObject;

   }

   catch (IOException e) {

    Log.w(getClass().getSimpleName(), "Error for URL " + url, e);

    setIsNetError(true);

   }

  }

  else

  {

   setIsNetError(true);

  }

  return mFilledObject;

 }



 /**

  * THIS IS FUNCTION FOR CHECKING INTERNET CONNECTION

  * @return TRUE IF INTERNET IS PRESENT ELSE RETURN FALSE

  */

 public boolean checkInternetConnection(Context context) {

  ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);



  if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {

   return true;



  } else {

   return false;

  }

 }



 public static void displayInternetNotAvailableMessage(final Context c) {

  ((Activity)c).runOnUiThread(new Runnable() {

   

   @Override

   public void run() {

    Toast.makeText(c, c.getString(R.string.error_internet), Toast.LENGTH_LONG).show();

   }

  });

 }


}





Now to use this class you have to write below code in your activity.


GetBoolean mBoolean = new GetBoolean();
List<NameValuePair> mNameValuePairs = new ArrayList<NameValuePair>();
mNameValuePairs.add(new BasicNameValuePair("key", "value"));
mBoolean = (GetBoolean) mHttpPostGetData.getFilledObject(getString(R.string.url), mNameValuePairs, mBoolean, mActivity);

if(mBoolean.getResult() != null && mBoolean.getResult().equals("true")) {
 Log.d("Response", "successfully");

}else {
 Log.d("Response", "Error");
}

So for each type of json you do not have to create Gson object and worry about the casting of the Object.
The above class will get the response from the server and then fill the bean class and then it will return you filled object.

If anything wrong or any suggestions, Please comment me.
Enjoy thanks.


2 comments:

  1. great!

    i dont know your mFiledObject called "GetBoolean".
    please tell me What is GetBoolean Class

    thank you.!!

    ReplyDelete
  2. GetBoolean is the model class with getter and setter methods
    This class will contains all the variables which the json response contains like

    class GetBoolean {
    boolean result;

    public boolean getResult() {
    return result;
    }

    public setResult(boolean result) {
    this.result = result;
    }

    }

    ReplyDelete