Friday, March 12, 2010

Androind JSON Parser

In this blog explain the steps to parse JSON object in android. We are discuss the following items
Overview of JSON
Syntax of JSON
Android JSON Support
Steps to Parse JSON data
Sample Application

Overview of JSON [JavaScript Object Notation]
    Lightweight data-interchagable format
    Text format that is completely language independent
   

JSON is built on two structures:

    * A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

    * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Syntax of JSON
Object {name1 : Value1 , name2 : Value2 , name3 : Value3 } -Normal Object Collection

Object [{name1_1 : Value , name1_2 : Value1 , name1_3 : Value2 }
    {name2_1 : Value , name2_2 : Value1 , name2_3 : Value2 } ] - Array Based



Example :
 {"menu": {
      "id": "file",
      "value": "File",
      "popup": {
        "menuitem": [
          {"value": "New", "onclick": "CreateNewDoc()"},
          {"value": "Open", "onclick": "OpenDoc()"},
          {"value": "Close", "onclick": "CloseDoc()"}
        ]
      }
}}


Android JSON Support
    Android already contains the required JSON libraries. The Following class are used to parse the JSON Object.

    JSONArray          A JSONArray is an ordered sequence of values.
    JSONObject        A JSONObject is an unordered collection of name/value pairs.
    JSONStringer     JSONStringer provides a quick and convenient way of producing JSON text.
    JSONTokener     A JSONTokener takes a source string and extracts characters and tokens from it.


Steps to Parse JSON data
1. Create a JSON Object and Convert JSONString to JSON Object
    JSONObject jObject = new JSONObject(jsonString);
   
2. Create a Key based JSONObject.
    JSONObject menuObject = jObject.getJSONObject("menu");

3. Get the Value
    Log.d("ID", menuObject.getString("id"));
    Log.d("Value ", menuObject.getString("value"));


Sample Application

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String myJsonContent = "{\"menu\": {\"id\": \"file\",\"value\": \"File\",\"popup\": {\"menuitem\": [{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},{\"value\": \"Open\",\"onclick\": \"OpenDoc()\"},{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
        sampleJsonParser(myJsonContent);
    }

    public void sampleJsonParser(String jsonString) {
        try {
            JSONObject jObject = new JSONObject(jsonString);
            JSONObject menuObject = jObject.getJSONObject("menu");
            Log.d("ID", menuObject.getString("id"));
            Log.d("Value ", menuObject.getString("value"));
            JSONObject popupObject = menuObject.getJSONObject("popup");
            JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
            for (int i = 0; i < 3; i++) {
                Log.d("Name", menuitemArray.getJSONObject(i).getString("value")
                        .toString());
                Log.d("Value", menuitemArray.getJSONObject(i).getString(
                        "onclick").toString());
            }
       } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}




8 comments:

  1. how to parse josn arrray in side json array?

    ReplyDelete
  2. good tutorial, very useful
    thanks

    ReplyDelete
  3. Jaon parse library

    http://www.c0de.com.ar/android-library.php

    ReplyDelete
  4. It is good tutorial and very use full to us.

    ReplyDelete
  5. getJSONObject(i) here u can pass only String key i is integer how u didnt got any error

    ReplyDelete
  6. Hey i have also written an article on Android JSON Parsing, here it is: http://www.technotalkative.com/android-json-parsing/ , hope it is helpful to others.

    ReplyDelete