Saturday, 2 March 2013

Simple Json Parser in Android

Java Class:private JSONObject jObject;
        private String jString = "{\"itemmenu\":    {" +
                "\"itemid\": \"file\"," +
                " \"itemvalue\": \"File\"," +
                " \"itemarray\": { \"menuitem\": " +
                "[ " + "{\"value\": \"New\"  , " + 
                "\"onclick\": \"CreateNewDoc()\"}, " +
                " {\"value\": \"Open\"," + 
                " \"onclick\":" + " \"OpenDoc()\"}," +
                "{\"value\": \"Close\"," +
                " \"onclick\": \"CloseDoc()\"}" +
                "]}" +
                "}" +
                "}";

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
                parse();
            }
        catch (Exception e)
            {
                e.printStackTrace();
            } }
   
     private void parse() throws Exception {

//Create json object and use it to retrieve the data in it
      jObject = new JSONObject(jString);
      JSONObject menuObject = jObject.getJSONObject("itemmenu");
      String attributeId = menuObject.getString("itemid");
      System.out.println("THE ATTRIBUTE ID   IS.....1....."+attributeId);
      String attributeValue = menuObject.getString("itemvalue");
      System.out.println("THE ATTRIBUTE ID  IS.....2....."+attributeValue);
      JSONObject popupObject = menuObject.getJSONObject("itemarray");
      JSONArray menuitemArray =  popupObject.getJSONArray("menuitem");
      for (int i = 0; i < 3; i++) {
         System.out.println("THE ATTRIBUTE ID IS.....3....."+menuitemArray.getJSONObject(i)
                               .getString("value").toString());
         System.out.println("THE ATTRIBUTE ID IS.....4....."+menuitemArray.getJSONObject(i)
                               .getString("onclick").toString());
            } } }
The output is shown in Logcat:
                                         

No comments:

Post a Comment