JSON Parsing in Android

Before moving on to JSON parsing in andorid, lets just take a brief about JSON. JSON stands for JavaScript Object Notation. It is a format used for information exchange, widely used in webservices as an alternative to XML. A simple example of a JSON file is as below :-

{
"responseData" :[
     {
      "name":
        {
          "firstname":"Vivek"
          "lastname":"Maskara"
        },
       "age":21
     },
     {
     {
      "name":
        {
          "firstname":"Ashish"
          "lastname" :"Kumar"
        },
       "age":21
     }
    ]
}

A simple JSON file consists of an array (named as JSONArray), an object (named as JSONObject) and and tags or keys, depending on the notation used.

The above file consists of a JSONObject “responseData”, followed by ‘[’ and ended with ‘]’, a JSONObject , “name”. An object can have multiple objects inside it. It can also have arrrays, or simply tags inside it. Basically every JSON file is formed by nesting Objects and Arrays inside on another, leading finally into individual tags.

Now, to reach out a tag, we must first traverse all its parents and its only then, that we can access the tag.

Every element in JSON is in the form of a “name” :”value”, pair. The name denotes the tag and the value denotes the values which we expect when we access the tag.

Consider a case, where we call a web service and we need to play with its response. The resposne, although is JSON encoded, needs to be stored as a String.Let us assume that the above file is stored in String response.

As we can see, the above JSON file begins with an array, “responseData”. So, the String response, needss to be stored in some JSONArray as below,

JSONArray responseData=new JSONArray(response);

As we have now moved out to the array, we need to find out the number of elements in this array.

int lenght = responseData.length();

We are going to use this variable length to traverse through the entire array as follow :

for(int i=0;i<lenght;i++)
{

}

Now inside the form loop we need to parse theb elements of the array responseData. Let us now make a model class which would be used to hold this value. Let us name this class as Record

Create a new Class in Java as Record.java

public class Record //Class Declaration
{
    static String First_Name;;
    static String Last_Name;
    static int age;
    public Record(String fName, Sting lName, int age)
    {
        this.First_Name=fname;
        this.Last_Name=lName;
        this.age=age;
    }
         
    public void setFirstName(String name)
    {
        this.FirstName=name; 
    }
        
    public String getFirstName()
    {
        return First_Name;
    }

    public void setLastName(String name)
    {
        this.LastName=name; 
    }
    public String getLastName()
    {
        return  Last_Name;
    }

    public int getAge()
    {
        return this.age;
    }

    public void setAge(int age)
    {
        this.age=age;
    }
}

Now we are going to use this class to hold the value of our responseData. In order to do that, we need to make a two objects as below:-

ArrrayList<Record> records=new ArrayList<Record>();
Record record=new Record();

The ArrayList is used to hold multiple values, similar to arrays in java, but having the capability to hold custom data-typed values. Now Coming back to the parsing section,

for (int i=0;i<length;i++)
{
  JSONObject name=responseData.getJSONObject("name");  //Direct child of responseData
  String fName=name.getString("firstname"); //Direct child of name
  String lname=name.getString("lastname");//Direct child of name
  int age=responseData.getInt("age")//Direct child of responseData
  record=new Record(fName,lName,age);
  records.put(record);
  i++;
}

Typically, we can put this inside a function say, parseJSON as shown below:-

public ArrayList<Record> parseJSON(Sring resposneData)
{
ArrrayList<Record> records=new ArrayList<Record>();
Record record=new Record();
try{
       JSONArray responseData=new JSONArray(response);
       int lenght-responseData.length();
       for (int i=0;i<length;i++)
       {
        JSONObject name=responseData.getJSONObject("name");  //Direct child of responseData
        String fName=name.getString("firstname"); //Direct child of name
        String lname=name.getString("lastname");//Direct child of name
        int age=responseData.getInt("age")//Direct child of responseData
        record=new Record(fName,lName,age);
        records.put(record);
        i++;
      }
   }
}

Now the entire data of your resposne is stored in ArrayListRecords, whichever function calls parseJSOn with paramaters as resposne, gets the return vales as records, accordingly.

Following is the example of such a function:-

public void display()
{
  ArrayList<Record> records= parseJson(response);
  int length=records.length();
  for(int i=0; i<length;i++)
   {
   Record record=new Record();
   record=records.get(i);
   System.out.println("Details of Candidate with ID : "+i+1);
   System.out.println("Name  : "+record.getFirstName()+" " +record.getLastName());
   System.out.println("Age     :"+record.getAge()); 
   System.out.println();
   i++;
  }
 }

Output :-

Details Of Candidate with ID : 1

Name :Vivek Maskara

Age :21

Details Of Candidate with ID : 2

Name :Ashish Kumar

Age :21

I am pursuing my BTech in IT from MIT, Pune and am an enthusiastic Android Developer.

This content has been helpful to you?

Thanks for contributing!

Yes No