Archive for May, 2012

JSON Parsing in android

Posted: May 23, 2012 in Android

Hello folks, this is how JSON parsing works in android, you just have to follow these few steps!!

e.g., this is JSON,

{
    "Info": {
        "1": {
            "id": "1",
            "name": "xyz",
            "phone_no": "4803578181",
            "address": "asdf",
            "lat": "33.384692",
            "long": "-111.598151"
        }
    }
}

String jsonParse = getJSONfromURL("your URL");  
/*here getJSONfromURL is function, u have to create it globally or locally in your program*/
Log.i(tag,"converted url:"+jsonParse);
JSONObject json;
String id, name,phone_no,address,lat,lon;
try{
       json = new JSONObject(jsonParse);
       JSONObject image = json.getJSONObject("Info");
       JSONObject subJson = image.getJSONObject("1");
       id = subJson.getString("id");
       name = subJson.getString("name");
       phone_no = subJson.getString("phone_no");
       address = subJson.getString("address");
       lat = subJson.getString("lat");
       lon = subJson.getString("long");
}
catch(Exception e){
       System.out.println(e.printStackTrace());
}

//getJSONfromURL function

public static String getJSONfromURL(String url){

       //initialize
       InputStream is = null;
       String result = "";
       JSONObject jArray = null;

       //http post
       try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

       }catch(Exception e){
            Log.e(tag, "Error in http connection "+e.toString());
       }

       //convert response to string
      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();
           result=sb.toString();
      }catch(Exception e){
      Log.e(tag, "Error converting result "+e.toString());
     }

      //try parse the string to a JSON object
      try{
          jArray = new JSONObject(result);
      }catch(JSONException e){
        Log.e(tag, "Error parsing data "+e.toString());
      }

      //return jArray;
      return result;
    }
Advertisements