从HTTP响应获得JSON对象 [英] get JSON object from a HTTP response

查看:716
本文介绍了从HTTP响应获得JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个HTTP的JSON对象获得响应:

I want to get a JSON object from a http get response:

下面是我目前的code的HTTP GET:

Here is my current code for the 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功能:

Here is the convertSteamToString function:

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对象回来了。

Right now I am just getting a string object. How can I get a JSON object back.

推荐答案

这是你得到的是仅仅是JSON Object.toString()的字符串。这意味着你的JSON对象,但在一个字符串格式。

The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.

如果您应该得到一个JSON对象你可以把:

If you are supposed to get a JSON Object you can just put:

JSONObject myObject = new JSONObject(result);

这篇关于从HTTP响应获得JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆