Friday 27 January 2012

parsing josn string [{"id":"1","title":"Appleade","description":""},{"id":"2","title":"Orange Juice","description":""},{"id":"3","title":"Black Orange","description":"Sweet Orange with seasonal black grape"},{"id":"4","title":"Green Juice","description":"Sweet Orange with seasonal green grape"}]


String Url = "http://192.168.10.5/restaurant/webservice/get-items.php?api_key=08tE8bnT9PPVwTxRCUnD6rMJE4r5ZYpImxJPPiBL&time=1327661277";
getJSONfromURL(Url);

public static void getJSONfromURL(String url) {

// initialize
InputStream is = null;
String result = "";
JSONArray 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("log_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("log_tag", "Error converting result " + e.toString());
}

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

// return jArray;
try {
// Get the element that holds the earthquakes ( JSONArray )
// JSONObject jObject;
// jObject = jArray.getJSONObject(i);
items = new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
// items[i] = (String) jObject.getString("title").toString();
items[i] = jArray.getJSONObject(i).getString("title")
.toString();
Log.e("item", items[i]);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}