JSON parsing in Android

JSON stands for javascript object notation.It is used to exchange the data between the server and our application.

JSON is the best alternative of XML.It is easy to use and understand.

We can send the data to the server and retrieve data from the server very easily with the help of JSON.

Here Android provides the different classes such as JSONObject,JSONArray and JSONStringer etc.

Formate of JSON is given below:

{
"subject":
{
"subjectone":"math",
"subjecttwo":"hindi",
"subjectthree":"english"
},
"operatingsystem":[
{
"operatingone":"android",
"operatingtwo":"linux",
"operatingthree":"mac"
}
]
}

Explanation of JSON formate:

1.Here ‘{‘ symbol indicates the JSON Object.

2.Here ‘[‘ symbol indicates the JSON Array

3.It contains two parameter key and value

Example:”operatingone”:”android”

Here “operating” is a key/parameter and “android” is the value.

# Now We will learn JSON parsing

JSON parsing means simply we ca say that getting/fetching data from URL.

#Now,For parsing the JSON object ,first we make object of JSONOject class and specify the JSON data.

Syntax:

String url;//url means the above complete json code

JSONOject response=new JSONObject(url);

Now will access the data with the help of key/parameter.

//Here getting the data from the JSON object name as "subject". 
JSONOject jsonobject1=response.getJSONObject("subject");

String obj1= jsonobject.getString("subjectone");
String obj2=jsonobject.getString("subjecttwo");
String obj3=jsonobject.getString("subjectthree");

Output:

math
hindi
english

#Now,For parsing the JSON Array ,first we make object of JSONArray class and specify JSON data.

//getting the json object inside the array
JSONArray jsonarray=response.getJSONArray("operatingsystem");

for(int i=0;i<jsonarray.lenght();i++)
{
JSONObject jsonobject2=jsonarray.getJSONObject(i);
//The above code objects are in the only in 0 index.if more object are the you can do same as below code.
String os1=jsonobject2.getString("operatingone");
String os2=jsonobject2.getString("operatingtwo");
String os3=jsonobject2.getString("operatingthree");
}

Output:

android
linux
mac

sumankumar80

Hello Friends,I have written and developed this website because you can learn technology easily ,prepare for the placement and also for the any type of examination . By :Suman Kumar

Leave a Reply

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