AdSense

AdSense3

Saturday, 10 October 2015

Android JSON Parser

JSON (Javascript Object Notation) is a programming language . It is minimal, textual, and a subset of JavaScript. It is an alternative to XML.

Android provides support to parse the JSON object and array.

Advantage of JSON over XML

1) JSON is faster and easier than xml for AJAX applications.
2) Unlike XML, it is shorter and quicker to read and write.
3) It uses array.

json object

A JSON object contains key/value pairs like map. The keys are strings and the values are the JSON types. Keys and values are separated by comma. The { (curly brace) represents the json object.
  1. {  
  2.     "employee": {  
  3.         "name":       "sachin",   
  4.         "salary":      56000,   
  5.         "married":    true  
  6.     }  
  7. }  

json array

The [ (square bracket) represents the json array.
  1. ["Sunday""Monday""Tuesday""Wednesday""Thursday""Friday""Saturday"]  
Let's take another example of json array.
  1. "Employee" :  
  2.     [  
  3.      {"id":"101","name":"Sonoo Jaiswal","salary":"50000"},  
  4.      {"id":"102","name":"Vimal Jaiswal","salary":"60000"}  
  5.     ]   
  6. }  

Example of android JSON parsing

activity_main.xml

Drag the one textview from the pallete. Now the activity_main.xml file will look like this:
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/textView1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginLeft="75dp"  
  14.         android:layout_marginTop="46dp"  
  15.         android:text="TextView" />  
  16.   
  17. </RelativeLayout>  

Activity class

Let's write the code to parse the xml using dom parser.
File: MainActivity.java
  1. package com.javatpoint.jsonparsing;  
  2.   
  3. import org.json.JSONException;  
  4. import org.json.JSONObject;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.widget.TextView;  
  8.   
  9. public class MainActivity extends Activity {  
  10. public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";  
  11.   
  12. @Override  
  13. public void onCreate(Bundle savedInstanceState) {  
  14. super.onCreate(savedInstanceState);  
  15. setContentView(R.layout.activity_main);  
  16.   
  17. TextView textView1=(TextView)findViewById(R.id.textView1);  
  18.   
  19. try{  
  20. JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");  
  21. String empname=emp.getString("name");  
  22. int empsalary=emp.getInt("salary");  
  23.   
  24. String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;  
  25. textView1.setText(str);  
  26.   
  27. }catch (Exception e) {e.printStackTrace();}  
  28.   
  29. }  
  30.   
  31. }  

Output:

android json parsing

Parsing JSONArray in Android

By the help of JSONArray class, you can parse the JSONArray containing the JSON Objects. Let's see the simple example to parse the json array.
File: MainActivity.java
  1. package com.example.jsonparsing2;  
  2.   
  3. import org.json.JSONArray;  
  4. import org.json.JSONException;  
  5. import org.json.JSONObject;  
  6. import android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.widget.TextView;  
  9.   
  10. public class MainActivity extends Activity {  
  11.    @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.          super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.            
  16.         TextView output = (TextView) findViewById(R.id.textView1);  
  17.            
  18.         String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\",\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";  
  19.           
  20.                String data = "";  
  21.                try {  
  22.                      // Create the root JSONObject from the JSON string.  
  23.                    JSONObject  jsonRootObject = new JSONObject(strJson);  
  24.   
  25.                    //Get the instance of JSONArray that contains JSONObjects  
  26.                     JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");  
  27.                      
  28.                     //Iterate the jsonArray and print the info of JSONObjects  
  29.                     for(int i=0; i < jsonArray.length(); i++){  
  30.                         JSONObject jsonObject = jsonArray.getJSONObject(i);  
  31.                            
  32.                         int id = Integer.parseInt(jsonObject.optString("id").toString());  
  33.                         String name = jsonObject.optString("name").toString();  
  34.                         float salary = Float.parseFloat(jsonObject.optString("salary").toString());  
  35.                            
  36.                         data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";  
  37.                       }  
  38.                     output.setText(data);  
  39.                  } catch (JSONException e) {e.printStackTrace();}  
  40.       }  
  41. }  

Output:

android json array parsing

1 comment:

  1. my teacher says that this topic is most important in company.
    kundan, you explained it very well
    But i am also looking for a rich content of this topic

    ReplyDelete