parse json file in android from asset

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 assetsfolder.

2. Reading Text File (from assets folder)

Before we start parsing the above JSON data, first we need to store data from jsondata.txtfile 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(
String temp;
while ((temp = br.readLine()) != null)
} catch (IOException e) {
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {

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




  1. yamuna devi · August 24, 2014

    If this Text file contains image how can i parse that image to image view?

    • LEON · August 25, 2014

      Json is just a place storing your ‘String’ values which could be the path of you IMAGE.
      Not sure what you have.

      If you have path of image then use

      If you have image in the form of bitmap then use

      If you have image in the form of drawable then use

      If you have image presents in drawable folder then use

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s