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(
"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();
}

FROM HERE

2 Comments Add yours

  1. yamuna devi says:

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

    1. LEON says:

      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
      imageview.setImageURI(Uri.parse(“pathofimage”));

      OTHERWISE:
      If you have image in the form of bitmap then use
      imageview.setImageBitmap(bm);

      If you have image in the form of drawable then use
      imageview.setImageDrawable(drawable);

      If you have image presents in drawable folder then use
      imageview.setImageResource(R.drawable.image);

Leave a comment