I want to retrieve JSON from a web-service and parse it then.
Am I on the right way?
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// parsing JSON
}
} catch (Exception e) {
}
Unfortunately I don't know how to convert HttpEntity
into a JSONObject.
This is my JSON (extract):
{
"names": [
{
"name": "Zachary"
},
{
"name": "Wyatt"
},
{
"name": "William"
}
]
}
To read the content from the entity, you can either retrieve the input stream via the HttpEntity. getContent() method, which returns an InputStream, or you can supply an output stream to the HttpEntity. writeTo(OutputStream) method, which will return once all content has been written to the given stream.
To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.
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) {
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With