从 HTTP 响应中获取 JSON 对象

Posted

技术标签:

【中文标题】从 HTTP 响应中获取 JSON 对象【英文标题】:Get a JSON object from a HTTP response 【发布时间】:2013-08-07 02:03:58 【问题描述】:

我想从 Http 获取响应中获取 JSON 对象:

这是我当前的 Http get 代码:

protected String doInBackground(String... params) 

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(params[0]);
    HttpResponse response;
    String result = null;
    try 
        response = client.execute(request);         
        HttpEntity entity = response.getEntity();

        if (entity != null) 

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            // now you have the string representation of the html request
            System.out.println("RESPONSE: " + result);
            instream.close();
            if (response.getStatusLine().getStatusCode() == 200) 
                netState.setLogginDone(true);
            

        
        // Headers
        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) 
            System.out.println(headers[i]);
        
     catch (ClientProtocolException e1) 
        // TODO Auto-generated catch block
        e1.printStackTrace();
     catch (IOException e1) 
        // TODO Auto-generated catch block
        e1.printStackTrace();
    
    return result;

这里是 convertSteamToString 函数:

private static String convertStreamToString(InputStream is) 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try 
        while ((line = reader.readLine()) != null) 
            sb.append(line + "\n");
        
     catch (IOException e) 
        e.printStackTrace();
     finally 
        try 
            is.close();
         catch (IOException e) 
            e.printStackTrace();
        
    
    return sb.toString();

现在我只是得到一个字符串对象。如何取回 JSON 对象。

【问题讨论】:

你在结果字符串中得到了什么? 你为什么要使用 response.getEntity() 两次? 要返回一个 JSON 对象,请不要连接到您连接的网络服务器以向您发送一个 JSON?它会这样做吗? @Zapnologica 检查我的答案。另请参阅 agen451 答案 【参考方案1】:

您得到的字符串只是 JSON Object.toString()。这意味着你得到了 JSON 对象,但是是 String 格式的。

如果你应该得到一个 JSON 对象,你可以放:

JSONObject myObject = new JSONObject(result);

【讨论】:

万一发生 HttpExchange ..? @Renan Bandeira 我正在尝试使用您的代码将我的 http 响应转换为 json 对象,我收到此错误 Error:(47, 50) java: incompatible types: java.lang.StringBuffer cannot be converted to java.util.Map @Karapapas 你能展示你的代码吗?我的回答是在 2013 年。我建议你使用 Retrofit 和 Gson/Jackson 来处理请求和 Json 序列化。 如何在 c# 中完成同样的任务?【参考方案2】:

执行此操作以获取 JSON

String json = EntityUtils.toString(response.getEntity());

更多细节在这里:get json from HttpResponse

【讨论】:

这是一个 String 而不是 JSON! 为什么会有这么多赞?这只是一个toString() 函数 - 基本上与 OP 所做的完全相同。 至少这摆脱了OP的很多低级开销代码。请参阅下面@Catalin Pirvu 的帖子以获得更完整的解决方案。【参考方案3】:

这不是您问题的确切答案,但这可能会对您有所帮助

public class JsonParser 

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) 
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try 
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) 
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            
         catch (Exception e) 
            e.printStackTrace();
        

        // RETURN LIST OF CLUBS
        return ret;
    


Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

【讨论】:

【参考方案4】:

如果不查看您的确切 JSON 输出,就很难为您提供一些工作代码。 This 教程非常有用,但您可以使用以下内容:

JSONObject jsonObj = new JSONObject("yourJsonString");

然后您可以使用以下方法从这个 json 对象中检索:

String value = jsonObj.getString("yourKey");

【讨论】:

非常好的教程。 “一般来说,所有 JSON 节点都以方括号或花括号开头。[ 和 之间的区别在于,方括号 ([) 表示 JSONArray 节点的开始,而花括号 () 表示 JSONObject。所以虽然访问这些节点我们需要调用适当的方法来访问数据。如果您的 JSON 节点以 [ 开头,那么我们应该使用 getJSONArray() 方法。如果节点以 开头,那么我们应该使用 getJSONObject() 方法。 【参考方案5】:

您需要使用JSONObject,如下所示:

String mJsonString = downloadFileFromInternet(urls[0]);

JSONObject jObject = null;
try 
    jObject = new JSONObject(mJsonString);
 
catch (JSONException e) 
    e.printStackTrace();
    return false;

...

private String downloadFileFromInternet(String url)

    if(url == null /*|| url.isEmpty() == true*/)
        new IllegalArgumentException("url is empty/null");
    StringBuilder sb = new StringBuilder();
    InputStream inStream = null;
    try
    
        url = urlEncode(url);
        URL link = new URL(url);
        inStream = link.openStream();
        int i;
        int total = 0;
        byte[] buffer = new byte[8 * 1024];
        while((i=inStream.read(buffer)) != -1)
        
            if(total >= (1024 * 1024))
            
                return "";
            
            total += i;
            sb.append(new String(buffer,0,i));
        
    
    catch(Exception e )
    
        e.printStackTrace();
        return null;
    catch(OutOfMemoryError e)
    
        e.printStackTrace();
        return null;
    
    return sb.toString();


private String urlEncode(String url)

    if(url == null /*|| url.isEmpty() == true*/)
        return null;
    url = url.replace("[","");
    url = url.replace("]","");
    url = url.replaceAll(" ","%20");
    return url;

希望对你有所帮助..

【讨论】:

您好 Apnologica.. 如果任何答案满足您的需要,请接受它,以便他人轻松获得正确答案。谢谢【参考方案6】:

为了彻底解决这个问题(是的,我知道这篇文章早就死了……):

如果你想要一个JSONObject,那么首先从result 获得一个String

String jsonString = EntityUtils.toString(response.getEntity());

那么你就可以得到你的JSONObject:

JSONObject jsonObject = new JSONObject(jsonString);

【讨论】:

【参考方案7】:

有一个 JSONObject 构造函数可以将 String 转换为 JSONObject:

http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)

【讨论】:

【参考方案8】:

如果你的api是response是一个java对象,那么你从Outputstream得到的字符串应该是json字符串格式比如

\"name\":\"xyz\", \"age\":21

。这可以通过多种方式转换为 JSON 对象,其中一种方法是使用 google GSON 库。 GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); &lt;javaobject&gt; = gson.fromJson(&lt;outputString&gt;, &lt;Classofobject&gt;.class);

【讨论】:

【参考方案9】:

没有 Gson 也可以做到这一点,使用实现 Json 树模型的 Jackson。

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(responseString);

【讨论】:

【参考方案10】:

1)String jsonString = EntityUtils.toString(response.getEntity()); 2)JSONObject jsonObject = new JSONObject(jsonString);

【讨论】:

正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于从 HTTP 响应中获取 JSON 对象的主要内容,如果未能解决你的问题,请参考以下文章

C# 使用 HttpClient 从 JSON 响应中获取特定对象

如何从打字稿中的json响应中获取日期对象

如何从片段中的 JSON 响应中的对象获取数据

从 Worklight 获取 HTTP 适配器的响应

无法从打字稿中的 json 对象获取数组响应

如何检查获取的响应是不是是javascript中的json对象