【问题标题】:How to convert HttpEntity into JSON?如何将 HttpEntity 转换为 JSON?
【发布时间】:2012-05-29 18:13:21
【问题描述】:

我想从网络服务中检索 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"
        }
    ]
}

【问题讨论】:

    标签: android json web-services


    【解决方案1】:

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

    【讨论】:

    • 上面写着Type mismatch: cannot convert from Object to String,所以我把它改成了String token = (String) result.get("token");。但不幸的是,当我尝试 Log.d("token", token); 时,我什么也没收到,尽管实体是 !=null 并且我有有效的 JSON。
    • 好的,你能把你的json feed链接发给我吗,因为你的json对象可能包含另一个JsonArray,那么你需要先使用JSONArray,然后从数组中提取值
    • 如果包含数组则添加 JSONArray tokenList = result.getJSONArray("result");JSONObject oj = tokenList.getJSONObject(0);String token = oj.getString("token");跨度>
    • EntityUtils 来自哪里?\
    • 对于EntityUtils,导入org.apache.http.util.EntityUtils;
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        试试这个

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

        【讨论】:

          【解决方案5】:
            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);   
                          }
                      }           
              }
          

          【讨论】:

            猜你喜欢
            • 2016-05-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-04
            • 2015-01-13
            • 2021-04-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多