Android JSON parsing example

JSON stands for JavaScript Object Notation which is an alternative to xml. It will be faster than xml and easy to read and write. Android provides support to parse JSON objects as well as JSON arrays. In this example let us learn how to parse JSON object and JSON arrays

Example 1 : How to parse JSON object in android.

Let us assume that following is your string which contains JSON object

{
    "student": {
            "name"  :  "ajith",
            "email" :  "ajith@gmail.com"
            "phone" :  "1234567894"
    }
}

So the above string contains JSON object student which consist of 3 strings and their values.We can parse it using the below code.

String student_data = "{"student": {"name":"ajith","email":"ajith@gmail.com","phone":"1234567894"}}"
try {
    JSONObject jsonObject = new JSONObject(student_data);
    JSONObject student_object = jsonObject.getJSONObject("student");

    String name = student_object.getString("name");
    String email = student_object.getString("email");
    String phone = student_object.getString("phone");

} catch (JSONException e) {
    e.printStackTrace();
}

Example 2 : How to parse JSON array in android.

//json array

String json_array_string = "{ \"students\" :[{\"id\":\"1\",\"name\":\"Ajith\",\"email\":\"ajith@gmail.com\"},{\"id\":\"2\",\"name\":\"Philip\",\"email\":\"philip@gmail.com\"}] }";

// start parsing the above JSON array

try {

JSONObject jsonObject = new JSONObject(json_array_string);
JSONArray student_array = jsonObject.getJSONArray("students");

for(int i = 0; i < student_array.length(); i++){

JSONObject student_object = student_array.getJSONObject(i);
String id = student_object.getString("id");
String name = student_object.getString("name");
String email = student_object.getString("email");

// you can add data to array list or hash map in each loop
}


} catch (JSONException e) {
e.printStackTrace();
}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *