如何将HttpEntity转换为JSON?

30

我想从一个web服务中获取JSON数据并解析它。
我是否走在正确的路上?

    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) {
    }

很遗憾我不知道如何将HttpEntity转换为JSONObject

这是我的JSON(摘录):

{
    "names": [
        {
            "name": "Zachary"
        },
        {
            "name": "Wyatt"
        },
        {
            "name": "William"
        }
    ]
}
5个回答

69

你可以将字符串转换为JSON格式:

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) {
  }

它说“类型不匹配:无法将Object转换为String”,所以我把它改成了String token = (String) result.get("token");。但不幸的是,当我尝试使用Log.d("token", token);时,我什么也没收到,尽管实体是!=null并且我有有效的JSON。 - Evgenij Reznik
好的,你能把你的JSON数据源链接发给我吗?因为有可能你的JSON对象包含另一个JsonArray,所以你需要先使用JSONArray,然后从数组中提取值。 - ρяσѕρєя K
nameList 是从哪里来的? - Evgenij Reznik
1
EntityUtils是从哪里来的? - Henley
1
对于EntityUtils,导入org.apache.http.util.EntityUtils; - JohnnyHuo
显示剩余2条评论

1
使用gson和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();
}

0
使用entity.getContent()方法获取InputStream并将其转换为String。

0
  public void responce() throws ClientProtocolException, IOException {
            org.apache.http.client.HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost("https://www.example.com/api/authenticate");
    
            List<NameValuePair> params = new ArrayList<NameValuePair>(2);
            
            params.add(new BasicNameValuePair("UserName", "anything"));
            params.add(new BasicNameValuePair("Password", "usepassworld"));
            
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
    
            if (entity != null){
               String string_1 = EntityUtils.toString(entity); 
               System.out.println("the token we are generated is -->"+ string_1);   
                }
            }           
    }

0

试试这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接