Our Feeds

Sunday, 8 March 2015

AJITH KP

JSON Parser Tool For Android

          JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This snippet will help you to parse JSON in Android.

          You need to download and import Apache Http Client libraries from here: https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

          Or add the line bellow in your build.gradle file.

android{
    compileSdkVersion xx
    buildToolsVersion 'xx.x.x'
    useLibrary  'org.apache.http.legacy'
}

JSON Page
JSON Data in Android Application

          Video Tutorial


          JSONTool.java

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;

import java.net.HttpCookie;
import java.util.List;

/**
 * Coded By AJITH KP [@ajithkp560]
 * Visit: www.terminalcoders.blogspot.com
 */
public class JSONTool {
    static InputStream is = null;
    static JSONObject jobj = null;
    static JSONArray  jarr = null;
    List<NameValuePair> params = null;
    String url;
    List<Cookie> cookies;
    String strCookie;
    String response;
    String method="get";
    boolean flg = false;
    JSONTool(String u)
    {
        url = u;
    }
    JSONTool()
    {

    }
    JSONTool(String u, List<NameValuePair> p)
    {
        params = p;
    }
    public void setUrl(String u)
    {
        url = u;
    }
    public void setParams(List<NameValuePair> p)
    {
        params = p;
    }
    public void setMethod(String m)
    {
        method = m.toLowerCase();
    }
    public JSONObject getJSONObject()
    {
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            if(params==null)
            {
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie",strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }

                httpResponse = httpClient.execute(httpGet);
            }
            else if(params!=null && method.equals("get"))
            {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url+="?"+paramString;
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }

                httpResponse = httpClient.execute(httpGet);
            }
            else
            {
                HttpPost httpPost = new HttpPost(url);
                if(flg)
                {
                    httpPost.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }

                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            if(!flg) {
                cookies = httpClient.getCookieStore().getCookies();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();

            Log.d("Message", response);
            jobj = new JSONObject(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jobj;
    }
    public JSONObject getJSONObject(String u, List<NameValuePair> l, String m)
    {
        params = l;
        method = m;
        url = u;
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            if(params==null)
            {
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpResponse = httpClient.execute(httpGet);
            }
            else if(params!=null && method.equals("get"))
            {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url+="?"+paramString;
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpResponse = httpClient.execute(httpGet);
            }
            else
            {
                HttpPost httpPost = new HttpPost(url);
                if(flg)
                {
                    httpPost.setHeader("Cookie", strCookie+";");
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                httpResponse = httpClient.execute(httpPost);
            }
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            if(!flg) {
                cookies = httpClient.getCookieStore().getCookies();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();

            Log.d("Message", response);
            jobj = new JSONObject(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jobj;
    }
    public String getString()
    {
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            if(params==null)
            {
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpResponse = httpClient.execute(httpGet);
            }
            else
            {
                HttpPost httpPost = new HttpPost(url);
                if(flg)
                {
                    httpPost.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                httpResponse = httpClient.execute(httpPost);
            }
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
            Log.d("Message", response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    public String getString(String u, List<NameValuePair> l, String m)
    {
        url = u;
        params = l;
        method = m.toLowerCase();

        params = l;
        method = m;
        url = u;
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            if(params==null)
            {
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpResponse = httpClient.execute(httpGet);
                httpEntity = httpResponse.getEntity();
            }
            else if(params!=null && method.equals("get"))
            {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url+="?"+paramString;
                HttpGet httpGet = new HttpGet(url);
                if(flg)
                {
                    httpGet.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpResponse = httpClient.execute(httpGet);
                httpEntity = httpResponse.getEntity();
            }
            else
            {
                HttpPost httpPost = new HttpPost(url);
                if(flg)
                {
                    httpPost.setHeader("Cookie", strCookie);
                }
                else {
                    cookies = httpClient.getCookieStore().getCookies();
                }
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                httpResponse = httpClient.execute(httpPost);
                httpEntity = httpResponse.getEntity();
            }

            is = httpEntity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();

            Log.d("Message", response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    public List<Cookie> getCookies()
    {
        return cookies;
    }

    public void setCookies(String c)
    {
        strCookie = c;
        flg = true;
    }
}

How To Use

           You can use the snippet in Android project. First save the code as JSONTool.java and import it to your package.

           Constructors

JSONTool tool = new JSONTool(); //Without argument
tool.setUrl("http://10.0.2.2/json.php"); //Setting URL
JSONTool tool = new JSONTool("http://10.0.2.2/json.php");//With url argument

            Set Parameter

tool.setParams(params);

           Set Method

tool.setMethod("get"); //method="get"
tool.setMethod("post"); //method="post"

           Getting JSONObject

JSONObject obj = tool.getJSONObject(); //You can use if the URL and Method is set. Else
JSONObject obj = tool.getJSONObject("http://10.0.2.2/json.php", params, "get");

            Getting JSON String

String res = tool.getString(); //You can use if the URL and Method is set. Else
String res = tool.getString("http://10.0.2.2/json.php", params, "get");

            Sample Code

package com.blogspot.terminal;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    TextView v;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        v = (TextView) findViewById(R.id.lbl);
        new sendPostData().execute();
    }

    private class sendPostData extends AsyncTask<String, Void, String>
    {
        JSONTool jtool = new JSONTool();
        String data;
        @Override
        protected String doInBackground(String... params) {

            try{
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("name","Ajith"));
                param.add(new BasicNameValuePair("mail","ajithkp560@gmail.com"));
                JSONObject obj = jtool.getJSONObject("http://10.0.2.2/ajith/json.php", param, "post");
                data = obj.getString("name")+" : "+obj.getString("email");
            }catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
            return data;
        }
        @Override
        protected void onPostExecute(String result) {
            //View your result here.
            v.setText(result);
        }
    }
}

4 comments

Write comments
Anonymous
AUTHOR
8 March 2015 at 05:11 delete

Good tutorial on json parser..... keep it up.....

Reply
avatar
Anonymous
AUTHOR
12 March 2015 at 21:19 delete

good tutorial on json parser. but video tutoial 'll be better.

Reply
avatar
AJITH KP
AUTHOR
14 March 2015 at 06:21 delete

thanks for your suggestion and i'll do it.. thanks and pls visit regularly... (f)

Reply
avatar
Anonymous
AUTHOR
10 June 2015 at 03:54 delete

simple json parser for android. thanks

Reply
avatar