Android JSON Parsing with Examples

  Keywords : Android json parsing can be done by using jsonobject and jsonarray in android applications, Android parse json data and show it in listview with examples

Here we will learn json parsing in android with examples and how to use android JSON library (JSONObject, JSONArray, JSONStringer, JSONTokenizer) objects to parse the JSON data and show it in android listview with examples.

Android JSON Parsing

Generally, JSON (JavaScript Object Notation) is one of the simplest data exchange format to interchange the data from server and it’s a best alternative for XML. In simple words, we can say that JSON is a light weight and structured language.

 

Android provides a support for all JSON classes such as JSONObject, JSONArray, JSONStringer, etc. to parse the JSON data to get a required information in android applications.

 

The main advantage of JSON is, it’s a language independent and the JSON object will contains a data like key / value pair.

 

Following is the sample structure of JSON data in android applications.

 

{

"users": [

{

"name": "Suresh Dasari",

"designation": "Team Leader",

"location": "Hyderabad"

},

{

"name": "Rohini Alavala",

"designation": "Agricultural Officer",

"location": "Guntur"

}

]

}

Generally, the JSON nodes will start with a square bracket ([) or with a curly bracket ({). The difference between square bracket and curly bracket is, the square bracket ([) represents the starting of a JSONArray node, whereas curly bracket ({) represents a JSONObject so we need to call appropriate method to get the data.

 

In case, if JSON data starts with [, then we need to use getJSONArray() method to get the data, same way if it starts with {, then we need to use getJSONObject() method.

JSON Parsing in Android

To parse the JSON data in android, we need to create an instance of JSONObject and JSONArray objects with a string that contains JSON data in it.

 

Following is the code snippet of parsing the JSON data in android using JSONObject and JSONArray objects to get the required information from JSON objects.

 

JSONObject jObj = new JSONObject(jsonStr);
JSONArray jsonArry = jObj.getJSONArray(
"users");
for(int i=0;i<jsonArry.length();i++){
    HashMap<String,String> user =
new HashMap<>();
    JSONObject obj = jsonArry.getJSONObject(i);
    user.put(
"name",obj.getString("name"));
    user.put(
"designation",obj.getString("designation"));
    user.put(
"location",obj.getString("location"));
    userList.add(user);
}

If you observe above code snippet, we used JSONObject and JSONArray objects to parse the data to get required information from a string that contain a JSON data.

 

Now we will see how to parse JSON string and bind the parsed JSON to Listview in android application with examples.

Android JSON Parsing Example

Following is the example of parsing the JSON string and get the required information from it using JSON classes in android applications.

 

Create a new android application using android studio and give names as JsonParserExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Now open activity_main.xml file from your \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="fill_parent"
   
android:layout_height="fill_parent"
   
android:orientation="vertical" >
    <
ListView
       
android:id="@+id/user_list"
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content"
       
android:dividerHeight="1dp" />
</
LinearLayout>

After that create an another layout file (list_row.xml) in /res/layout folder to show the data in listview, for that right click on layout folder à add new Layout resource file à Give name as list_row.xml and write the code like as shown below.

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="fill_parent"
   
android:layout_height="wrap_content"
   
android:orientation="horizontal"
   
android:padding="5dip" >
    <
TextView
       
android:id="@+id/name"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textStyle="bold"
       
android:textSize="17dp" />
    <
TextView
       
android:id="@+id/designation"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_below="@id/name"
       
android:layout_marginTop="7dp"
       
android:textColor="#343434"
        
android:textSize="14dp" />
    <
TextView
       
android:id="@+id/location"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignBaseline="@+id/designation"
       
android:layout_alignBottom="@+id/designation"
       
android:layout_alignParentRight="true"
       
android:textColor="#343434"
       
android:textSize="14dp" />
</
RelativeLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.jsonparserexample path and write the code like as shown below

MainActivity.java

package com.tutlane.jsonparserexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        String jsonStr = getListData();
       
try{
            ArrayList<HashMap<String, String>> userList =
new ArrayList<>();
            ListView lv = (ListView) findViewById(R.id.
user_list);
            JSONObject jObj =
new JSONObject(jsonStr);
            JSONArray jsonArry = jObj.getJSONArray(
"users");
           
for(int i=0;i<jsonArry.length();i++){
                HashMap<String,String> user =
new HashMap<>();
                JSONObject obj = jsonArry.getJSONObject(i);
                user.put(
"name",obj.getString("name"));
                user.put(
"designation",obj.getString("designation"));
                user.put(
"location",obj.getString("location"));
                userList.add(user);
            }
            ListAdapter adapter =
new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
            lv.setAdapter(adapter);
        }
       
catch (JSONException ex){
            Log.e(
"JsonParser Example","unexpected JSON exception", ex);
        }
    }
   
private String getListData() {
        String jsonStr =
"{ \"users\" :[" +
               
"{\"name\":\"Suresh Dasari\",\"designation\":\"Team Leader\",\"location\":\"Hyderabad\"}" +
               
",{\"name\":\"Rohini Alavala\",\"designation\":\"Agricultural Officer\",\"location\":\"Guntur\"}" +
               
",{\"name\":\"Trishika Dasari\",\"designation\":\"Charted Accountant\",\"location\":\"Guntur\"}] }";
       
return jsonStr;
    }
}

If you observe above code, we used JSONObject and JSONArray objects to parse and get the required data from JSON string based on our requirements.

Output of Android JSON Parsing Example

When we run above program in android studio we will get the result like as shown below.

 

Android JSON Parsing Example Result

 

This is how we can parse JSON data in android applications to get the required information based on our requirements.