How to convert HttpEntity into JSON?

后端 未结 4 746
既然无缘
既然无缘 2020-12-09 08:44

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         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 09:11

    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();
    }
    

提交回复
热议问题