Wednesday 20 August 2014

Android JSON Parsing Tutorial

Example for JSON String
--------------------------------------------

[
{
    "title": "School",
    "image": "jpg",
    "url": "http://",
 
    "State": "ddddd",
    "Phone": [
         "2",
        "4",
        "5",
    ]
},
{
    "title": "School",
    "image": "jpg",
    "url": "http://",

    "State": "ddddd",
    "phone": [
        "2",
        "4",
        "5",
    ]
}

]



----------------------------------------------------------


Where { } Represent JSONObject and [ ] repesents JSONArray


Java Code
-----------------------------

 String strJson="** THE ABOVE JSON STRING **";


OR If your Json String is in an URL then

ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
String strJson = sh.makeServiceCall(url, ServiceHandler.GET);

              JSONArray mainArray = new JSONArray(strJson);

              for (int i = 0; i < mainArray.length(); i++) {
                  JSONObject sub = mainArray.getJSONObject(i);

                  String id = sub.getString("title");


                  String image = sub.getString("image");
                  String url=sub.getString("url");
                

                 

                  String State=sub.getString("State");

                  JSONArray genreArray=sub.getJSONArray("genre");

                  String genre1=genreArray.get(0).toString();
                  String genre2=genreArray.get(1).toString();
                  String genre3=genreArray.get(2).toString();
                


                  System.out.println("Id: "+id);
                  System.out.println("Image: "+image);
                  System.out.println("url: "+url);
               
               
                  System.out.println("State: "+State);
                  System.out.println("genre1: "+genre1);
                  System.out.println("genre2: "+genre2);
                  System.out.println("genre3: "+genre3);
                


              }


No comments:

Post a Comment