JSON Parsing in Android

1 min read

Android Development

JSON_vector_logo.svg

 

Today we are going to retrieve a JSON from a web url parse it and use it in our application.  The very first question is why JSON is used so heavily.

Short answer : Almost every computer language has built in functions to manipulate JSON. So it is easier for developers to parse JSON and utilise in program.

 

Long answer : JSON is very lightweight so it takes very less bandwidth to travel across the network. So it is faster than xml.

We will be coding in Android Studio with Java Language. To know about JSON syntax you can study Link

 

see below JSON

 

{
"list": {
"data": [
{
"ID": "1",
"USERNAME": "Thanks",
"FCMID": "eo5uBBIecUI:APA91bFUEnw-fe5Ow4xm3cY8ST2VWs2W4gg8PCG2qX4PqCzlJT1Y6eY5H2sPpUqAQlWyGW3w29VLsVQN7xjwvfeNT6OIEBfLc9gBcja-9Cubl4JnFQDtmYnd2_AZyaVEjz1ZeIKVzin2",
"EMAILID": "relsellglobal@gmail.com",
"userimage": "http://www.relsellglobal.in/chatapp/profileimages/userprofile.jpg"
}, ......
]
}
}

 

So in android we create POJO ( plain Old Java Objects) after visualising the JSON structure. In JSON structure above there is JSON Object at the root.

after that there is a JSON Object called list which has another JSON Array called data. This JSON Array will be having other JSON Objects.

Let create pojo’s

public class WebInnerPojo {
   String id;
   String username;
   String fcmId;
   .....
}

 

see below android java file

 

/*
 * Copyright (c) 2017. Relsell Global
 */

package in.relsellglobal.jsonparsingdemo;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<WebPojo> webPojoArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webPojoArrayList = new ArrayList<>();

        new JSONParsingTask().execute();
    }

    public class JSONParsingTask extends AsyncTask<Void,Void,String> {

        @Override
        protected String doInBackground(Void... params) {

            String url = "http://relsellglobal.in/DeliveryS/CRKInsightsServer/mobilecheck.php?controlVar=32";
            StringBuffer stringBuffer = new StringBuffer();

            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

                int code = connection.getResponseCode();

                if(code == HttpURLConnection.HTTP_OK) {

                    InputStream inputStream = connection.getInputStream();

                    String line = "";


                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                    while((line = bufferedReader.readLine()) != null) {
                        stringBuffer.append(line);
                    }

                    return stringBuffer.toString();

                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if(s!=null) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    JSONObject jsonObjectList = jsonObject.getJSONObject("list");
                    JSONArray jsonArray = jsonObjectList.getJSONArray("data");

                    for(int i=0;i<jsonArray.length();i++) {
                        JSONObject obj = (JSONObject) jsonArray.get(i);
                        WebPojo webPojo = new WebPojo();
                        webPojo.setId(obj.getString("ID"));
                        webPojo.setUsername(obj.getString("USERNAME"));
                        webPojo.setFcmId(obj.getString("FCMID"));
                        webPojoArrayList.add(webPojo);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

                System.out.println(webPojoArrayList);


            }


        }
    }


}

 

Source code of the application is available at : JSONParsingDemo

 

Thanks for reading.