public static String jsonTest(String Url){
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(Url);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
Now, You have your JSON in your result String.
Create a
JSONObject:
To get a specific stringJSONObject jObject = new JSONObject(
jsonTest("give your url")
);
String aJsonString = jObject.getString("your_string_name");
To get a specific double
double aJsonDouble = jObject.getDouble("your_double_name");
To
get a specific JSONArray JSONArray jArray = jObject.getJSONArray("your_array_name");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("string_name_in_the_array");
String oneObjectsItem2 = oneObject.getString("another_string_name_in_the_array");
} catch (JSONException e) {
// handle with care
}
}