Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HttpEntity into JSON?

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"
        }
    ]
}
like image 834
Evgenij Reznik Avatar asked May 29 '12 18:05

Evgenij Reznik


People also ask

How do you read HttpEntity data?

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.

How do I get response JSON?

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.


2 Answers

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) {
  }
like image 169
ρяσѕρєя K Avatar answered Oct 01 '22 13:10

ρяσѕρєя K


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();
}
like image 27
Mohammad Tbeishat Avatar answered Oct 03 '22 13:10

Mohammad Tbeishat