[Android] Simple Source code read JSON file on server - JSON parser

Public on March 5, 2015
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. If your app consuming XML data, you can always refer to Android XML Parsing Tutorial.
In this tutorial we are going to learn how to parse JSON in android.


You can get this JSON data by accessing http://thanhcs94.zz.vc/contacts

{
    "contacts": [
        {
                "id": "1",
                "name": "thanhcs94",
                "email": "nguyenvanthanh9294@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "2",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]
}


The difference between [ and { - (Square brackets and Curly brackets)

In general all the JSON nodes will start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.
If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.

So let's start by creating a new android project
1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. I had left my main activity name as MainActivity.java and gave the package name as info.androidhive.jsonparsing
2. As we are fetching the JSON by making HTTP calls, we need to add INTERNET permission in our AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.
<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demojsonparser"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET"/>
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.demojsonparser.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
create class JsonParser to get arrayt object from json.

JsonParser.java
InputStream is=null;
          JSONObject jobj=null;
          String json;



public JSONObject getJSONFromUrl(String url)
          {
                 try{
                        //khoi tao
                        DefaultHttpClient client=new DefaultHttpClient();
                        HttpPost httppost=new HttpPost(url);
                       
                        //thuc thi , lay ve noi dung
                        HttpResponse httpresponse=client.execute(httppost);
                        HttpEntity httpentity=httpresponse.getEntity();
                        is=httpentity.getContent();
                       
                        //doc du lieu
                        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();
                        json=sb.toString(); //doc StringBuilder vao chuoi
                       
                        jobj=new JSONObject(json); //dua chuoi vao doi tuong json
                       
                 }catch(Exception e)
                 {
                        Log.d("loi", e.toString());
                 }
                 return jobj;
          }


MainActivity.java

In my main activity class (MainActivity.java) I have declared all the JSON node names and created an instance for the list view.

Create variable .

public class MainActivity extends Activity {

 private static String url = "http://thanhcs94.zz.vc/contacts"; 
 JSONArray contacts = null; 
 // JSON Node names 
 private static final String TAG_CONTACTS = "contacts"; 
 private static final String TAG_ID = "id"; 
 private static final String TAG_NAME = "name"; 
 private static final String TAG_EMAIL = "email"; 
 private static final String TAG_ADDRESS = "address"; 
 private static final String TAG_GENDER = "gender"; 
 private static final String TAG_PHONE = "phone"; 
 private static final String TAG_PHONE_MOBILE = "mobile"; 
 private static final String TAG_PHONE_HOME = "home"; 
 private static final String TAG_PHONE_OFFICE = "office"; 

 //
 ListView lv;
 ArrayList<HashMap<String,String>> contactlist;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
       contactlist= new ArrayList<HashMap<String,String>>();
        lv =(ListView)findViewById(R.id.lv);
        new ChayNenLayJson().execute();
        
       
        lv.setOnItemClickListener(new OnItemClickListener() {

         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
           long arg3) {
          // TODO Auto-generated method stub
          String name=((TextView)arg1.findViewById(R.id.name)).getText().toString();
          Toast.makeText(getApplicationContext(),"ban chon "+name, Toast.LENGTH_SHORT).show();
         }
        });

      
    }

 
    class ChayNenLayJson extends AsyncTask<Void,Void,Void>
    {
  @Override
  protected Void doInBackground(Void... arg0) {
   JsonParser jsonparse=new JsonParser();
      //lay doi tuong json
      JSONObject jsonobject=jsonparse.getJSONFromUrl(url);
      try{
       //tao mang contacts
       contacts=jsonobject.getJSONArray(TAG_CONTACTS);
       
       Log.d("array", contacts.length()+" \n"+contacts.toString());
       //duyet tung contacts
       for(int i=0;i<contacts.length() ;i++)
       {
        JSONObject onecontact=contacts.getJSONObject(i);
        
       
        String id=onecontact.getString(TAG_ID);
           String name=onecontact.getString(TAG_NAME);
           String email=onecontact.getString(TAG_EMAIL);
           String address=onecontact.getString(TAG_ADDRESS);
           String gender=onecontact.getString(TAG_GENDER);

           
           JSONObject phone=onecontact.getJSONObject(TAG_PHONE);
           String mobile=phone.getString(TAG_PHONE_MOBILE);
           String home=phone.getString(TAG_PHONE_HOME);
           String office=phone.getString(TAG_PHONE_OFFICE);

           
        Log.d("dulieu","\nid: "+id +" name:"+name+"email:"+email+"address : "+address+"gender:"+gender+" mobile:"+mobile +"home:"+home+"office:"+office);
        HashMap<String,String> map=new HashMap<String,String>();
        map.put(TAG_ID, id);
        map.put(TAG_NAME, name);
        map.put(TAG_EMAIL,email);
        map.put(TAG_ADDRESS,address);
        map.put(TAG_GENDER,gender);
        map.put(TAG_PHONE_MOBILE,mobile);
        map.put(TAG_PHONE_HOME,home);
        map.put(TAG_PHONE_OFFICE,office);
        
        contactlist.add(map);
       }
       
      }catch(Exception e)
      {
       Log.d("loi",e.toString());
      }

   return null;
  }
  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   super.onPostExecute(result);
   ListAdapter adapter=new SimpleAdapter(MainActivity.this,
     contactlist,
     R.layout.listviewlayout,
     new String[]{TAG_NAME,TAG_EMAIL,TAG_PHONE_MOBILE,TAG_PHONE_HOME,TAG_PHONE_OFFICE},
     new int[]{R.id.name,R.id.email,R.id.mobile,R.id.home,R.id.office});
     lv.setAdapter(adapter);
     Log.d("lol", "Onpostexcuse");

  }
    }

}


file  listviewlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/mobile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/office"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>







[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon