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

以下是我当前的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;
}

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

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

推荐答案

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对象,你可以放:

JSONObject myObject = new JSONObject(result);

Json相关问答推荐

使用JOLT转换来卸载数据

如何循环访问多个子数组并在单个JSON中检索数据点

过go 24小时内判断员事件的EventBridge事件模式

创建Json嵌套文件 struct

在Ansible中从json中提取特定数据

NoneType 对象的 Python 类型错误

交换键和数组值,将旧键转换为新数组值,使用 jq

如何获取 JSON 对象字段值和同一 JSON 对象的下一个数组中的字段值?

使用不同行数的数据创建嵌套Jolt

如何按键过滤

使用 jq 将消息转换为数组

在 JOLT 中重新排列值

通过sql查询读取嵌套Json

为什么JsonConvert反序列化对象以int但不长失败

为什么在测试 RSPEC 时 JBuilder 不返回 JSON 中的响应正文

哪个更好:Json 或 XML (PHP)

使用 ajax 将 JSON 发送到 PHP

如何将有向无环图 (DAG) 存储为 JSON?

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

如何将 mysqli 结果转换为 JSON?