Friday, December 5, 2014

Android JSON Parsing Tutorial

There are many ways to get JSON data, In this tutorial I'm getting JSON data from a text file stored in assets folder alternatively you can also get JSON data from a URL or web service.


1. The JSON Structure


I am taking an example of following JSON which will give you list of employees and each employee will have details like id, name, city, gender, age etc.

{
    "employee": [
        {
            "id": 101,
            "name": "Amar",
            "city": "Dausa",
            "gender": "M",
            "age": 21
        },
        {
            "id": 102,
            "name": "Sunil",
            "city": "Bharatpur",
            "gender": "M",
            "age": 22
        },
        {
            "id": 103,
            "name": "Uday",
            "city": "Bharatpur",
            "gender": "M",
            "age": 22
        },
     
        {
            "id": 104,
            "name": "Rahul",
            "city": "Alwar",
            "gender": "M",
            "age": 21
        }
    ]
}

Consider that above JSON data is stored in jsondata.txt file which is stored in assets folder.


2. Reading Text File (from assets folder)


Before we start parsing the above JSON data, first we need to store data from jsondata.txt file to a string. Here is the code snippet-

// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsondata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}

String myjsonstring = sb.toString();


 3. Parsing JSON data from String


In second step we store JSON data from jsondata.txt file to a string called myjsonstring, Now we are ready to parse JSON data from it. Here is the code snippet-

// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);

// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");

// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {

// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);

// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String city = jsonObj.getString("city");
String gender = jsonObj.getString("gender");
int age = jsonObj.getInt("id");

}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Note:- The parsing of JSON data from URL is same as in step 3. If you want to parse JSON data from URL, first you need to download the JSON data from server using HTTP & then you need to store that data into a string. After that you can easily parse JSON data from that string (similar to step 3).


Final Code



Project Name : JsonFromString
Package : com.sunil.jsonfromstring
Main Activity : MainActivity.java
Layout : main.xml
Build Target : Android 2.2

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</RelativeLayout>


MainActivity.java
package com.sunil.jsonfromstring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

String myjsonstring;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Preparing TextView to display JSON results
TextView tvResult = (TextView) findViewById(R.id.tvResult);

// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsondata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}

myjsonstring = sb.toString();

// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);

// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");

// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {

// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);

// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String city = jsonObj.getString("city");
String gender = jsonObj.getString("gender");
int age = jsonObj.getInt("id");

// Append result to TextView
tvResult.append("ID : " + Integer.toString(id) + "\n");
tvResult.append("NAME : " + name + "\n");
tvResult.append("CITY : " + city + "\n");
tvResult.append("GENDER : " + gender + "\n");
tvResult.append("AGE : " + Integer.toString(age) + "\n\n");

}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


Output

android json


That's it ! You can also download the source code of this tutorial.

Download from here

Source