android - 如何将 HttpEntity 转换为 JSON?

标签 android json web-services

我想从 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"
        }
    ]
}

最佳答案

您可以将字符串转换为 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) {
  }

关于android - 如何将 HttpEntity 转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10804466/

相关文章:

android - 是否可以让多个服务器共享一个 Firebase Cloud Messaging 服务器 key ?

python - 在python中解析特殊的json

ajax - 如何在ajax中调用RESTful Web服务?

java - 如何阻止 Apache CXF 将基元转换为对象类型?

android - - ddms] 传输错误 : open failed:Permission denied

android - 将断言堆栈跟踪保存到文件

android - 如何将图像从设备上传到后端服务器?

javascript - 找到匹配项时遍历 JSON 对象并更新值的正确方法是什么

xml - JSON 是否有 +json 后缀约定?

java - 我如何在用java开发的rest web服务中返回json