I want to retrieve JSON from a web-service and parse it then.
Am I on the right way?
HttpClient httpclient = new DefaultHttpClient();
HttpGet htt
You can convert string to json as:
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONArray tokenList = result.getJSONArray("names");
JSONObject oj = tokenList.getJSONObject(0);
String token = oj.getString("name");
}
}
catch (Exception e) {
}
Use the entity.getContent() to get the InputStream and convert it to String.
Try this
public String getMyFeed(){
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclien.execute(httpget);
HttpEntity entity = response.getEntity();
HttpInputStream content = entity.getContent();
StatusLine sl = response.getStatusLine();
int statCode = sl.getStatusCode()
if (statCode ==200){
// process it
}
}
String readFeed = getMyFeed();
JSONArray jArr = new JSONArray(readFeed);
for(int i=0 ; i<jArr.length ; i++)
JSONObject jObj = jArr.getJSONObject(i);
Using gson and EntityUtils:
HttpEntity responseEntity = response.getEntity();
try {
if (responseEntity != null) {
String responseString = EntityUtils.toString(responseEntity);
JsonObject jsonResp = new Gson().fromJson(responseString, JsonObject.class); // String to JSONObject
if (jsonResp.has("property"))
System.out.println(jsonResp.get("property").toString().replace("\"", ""))); // toString returns quoted values!
} catch (Exception e) {
e.printStackTrace();
}