How to convert HttpEntity into JSON?

后端 未结 4 745
既然无缘
既然无缘 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 08:50

    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) {
      }
    
    0 讨论(0)
  • 2020-12-09 08:52

    Use the entity.getContent() to get the InputStream and convert it to String.

    0 讨论(0)
  • 2020-12-09 09:03

    Try this

    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);
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题