Friday 30 August 2013

JSON Parsing in Android

JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.

  Crate This Class For Parsing the URL

public class JSONParser
{
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONObject getJSONFromUrl(String url){
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            //Also try HttpPost httpPost=new HttPost();
            HttpGet httpget = new HttpGet(url);
            //Execute get/post object through httpClient and get HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpget);
            //get the Entity
            HttpEntity httpEntity = httpResponse.getEntity();
            //get the InputStream throug get Content....
            is = httpEntity.getContent();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (ClientProtocolException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        }catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        }catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}




Call From the Activity


JSONParser jParser = new JSONParser();

JSONObject jsonObj = jParser.getJSONFromUrl("http://www.example.com/myws/getData.html?id=12");

SONArray  jsonArray= jsonObj.getJSONArray("Name of the object");


Below is the basic jason format:

 {
     "contacts"
     [ 
        {                 
              "id": "AP9099", 
              "name": "Alpan Patel",                
              "email": "alpanpatel4am@gmail.com"
               "address": "Valsad",                     
              "gender" : "Male",
               "phone": {                    
                      "mobile": "+91 XXXX XXXX XX",
                        "home": "XX XXXXXXX",                    
                      "office": "XX XXXXXX"
                                }         
          },
     ] 
}