从HTTP响应中获取JSON对象

编程入门 行业动态 更新时间:2024-10-06 06:41:23
本文介绍了从HTTP响应中获取JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

这是我当前的代码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对象,但是是一种String格式。

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对象

本文发布于:2023-11-26 23:12:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635590.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   HTTP   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!