Sunday, May 12, 2013

Android Json Parsing Tutorial:




JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.




To do json parsing first of all you have the need to understand the structure of json .Following diagram illustrate the basic tags which we use repeatedly according to the need.














Below is the basic jason format: 



{
    "contacts": [
        {
                "id": "c200",
                "name": "Lucky Rana",
                "email": "luckyrana@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "deepak chettri@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]
}




Writing JSON Parser Class
In your project create a class file and name it as JSONParser.java. The parser class has a method which will make http request to get JSON data and returns a JSONObject.




JSONParser.java
package com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}




Json have only three data items which we use to retrieve data:



1. Json array
"contacts": [
        {
                "id""c200",
                "name""Lucky Rana",
                "email""luckyrana@gmail.com",
                "address""xx-xx-xxxx,x - street, x - country",
                "gender" "male",
                "phone": {
                    "mobile""+91 0000000000",
                    "home""00 000000",
                    "office""00 000000"
                }
        }]

To retrieve this "contact" array we use following syntex:

// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
// getting JSON string from URL
     JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray("contact");
 Log.d("Contact array Data",json.toString());
        
catch (JSONException e) 
{
             e.printStackTrace();
         }
2. Json object
"phone": {
                    "mobile""+91 0000000000",
                    "home""00 000000",
                    "office""00 000000"
                }
To retrieve this "phone" object data we use following syntex:
// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
// getting JSON string from URL
  JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray("contact");
 
// looping through All Contacts

            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);
                 
               

// Phone number is agin JSON Object

                JSONObject phone = c.getJSONObject(phone);
 
Log.d("Phone object Data",phone.toString());
               
        
catch (JSONException e) 
{
             e.printStackTrace();
         }

3. Json string
"id""c200"
To retrieve this "phone" object data we use following syntex:



// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();


// getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray("contact");
 // looping through All Contacts

            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);
                 
                // Storing each json item in variable
                String id = c.getString("id");
                String name = c.getString("name");
// Phone number is agin JSON Object

                JSONObject phone = c.getJSONObject(phone);
 
                String mobile = phone.getString("mobile");
                String home = phone.getString("home");
                String office = phone.getString("office");
              
Log.d("String Data",mobile.toString());
        
catch (JSONException e) 
{
             e.printStackTrace();
         }





Example 1:


Here is an example of  twitter json parsing using this url: 
http://search.twitter.com/search.json?q=android



11 comments:

  1. I am definitely enjoying your website. You definitely have some great insight and great stories. 
    python training institute in chennai
    python training in Bangalore
    python training in pune

    ReplyDelete
  2. I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favourites blog site list and will be checking back soon.

    java training in chennai | java training in bangalore


    java training in tambaram | java training in velachery

    ReplyDelete
  3. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  4. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ReplyDelete
  5. Your topic is very nice and helpful to us … Thank you for the information you wrote.

    Learn Hadoop Training from the Industry Experts we bridge the gap between the need of the industry. Bangalore Training Academy provide the Best Hadoop Training in Bangalore with 100% Placement Assistance. Book a Free Demo Today.
    Big Data Analytics Training in Bangalore
    Tableau Training in Bangalore
    Data Science Training in Bangalore
    Workday Training in Bangalore

    ReplyDelete
  6. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.sap abap training in bangalore

    ReplyDelete
  7. Some may stag in Interviews!!! OOPS!! More than 50% of students do this in their career. Instead, do Hadoop Training in Chennai at Infycle. Those students can easily clear this Interview session because more than 5 times at INFYCLE practicing mock-interview sessions, Hence students are Getting out of their interview fear.

    ReplyDelete