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();
        }
    }
}




12 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. This comment has been removed by the author.

    ReplyDelete
  7. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in android programming your post help me a lot.Thanks for your informative article. Best Android Training in chennai | Android Training in chennai

    ReplyDelete
  8. Very informative ..i suggest this blog to my friends..Thank you for sharingAndroid Training in chennai | Android Training

    ReplyDelete
  9. Thanks, Harsh for such a great post. I have tried and found it really helpful.

    Bangalore Training Academy is a Best Institute of Salesforce Admin Training in Bangalore . We Offer Quality Salesforce Admin with 100% Placement Assistance on affordable training course fees in Bangalore. We also provide advanced classroom and lab facility.

    ReplyDelete
  10. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.

    Agile coach certification
    ICP ACC certification online

    ReplyDelete