Sunday, May 12, 2013

Android Jason string parsing without any Array



Android Jason parsing without Array Name


A few good sights to learn simple jason parsing before learning this:
2.    http://www.vogella.com/articles/AndroidJSON/article.html


Below is an example of json without array 
[
  {
    "cnt":1,
    "name":"American",
    "pk":7
  },
  {
    "cnt":2,
    "name":"Celebrities",
    "pk":3
  },
  {
    "cnt":1,
    "name":"Female",
    "pk":2
  },
  {
    "cnt":1,
    "name":"Language",
    "pk":8
  },
  {
    "cnt":1,
    "name":"Male",
    "pk":1
  },
  {
    "cnt":1,
    "name":"Region",
    "pk":9
  }
Check out  my previous post 

Android Jason parsing without Array name


Android Jason parsing without Array Name


A few good sights to learn simple jason parsing before learning this:

Below is an example of json without array name :    
........
  [ { "cnt":1,
    "text":"American",
    "pk":7
  },
  {
    "cnt":2,
    "text":"Celebrities",
    "pk":3
  },
  {
    "cnt":1,
    "text":"Female",
    "pk":2
  },
  {
    "cnt":1,
    "text":"Language",    "pk":8
  },
  {
    "cnt":1,
    "text":"Male",    "pk":1
  },
  {
    "cnt":1,
    "text":"Region",    "pk":9
  }]

You don't need to call json.getJSONArray()like this  
// Getting Array of Contacts 

    contacts = json.getJSONArray("contacts");
 because the JSON you're working with already a Jsan array. So, don't construct an instance of JSONObject; Only you need to call

Hopeflly this example will help you in parsing jason array without  name.
package de.vogella.android.twitter.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class ParseJSON extends Activity {
  
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String readTwitterFeed = readTwitterFeed(); try { JSONArray jsonArray = new JSONArray(readTwitterFeed); Log.i(ParseJSON.class.getName(), "Number of entries " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Log.i(ParseJSON.class.getName(), jsonObject.getString("text")); } } catch (Exception e) { e.printStackTrace(); } } public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(ParseJSON.class.toString(), "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } }
Thanks.

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