如何从 Java HTTPResponse 解析 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2845599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse JSON from a Java HTTPResponse?
提问by Joe Ludwig
I have an HttpResponse object for a web request I just made. The response is in the JSON format, so I need to parse it. I can do it in an absurdly complex way, but it seems like there must be a better way.
我有一个 HttpResponse 对象,用于我刚刚提出的 Web 请求。响应是 JSON 格式,所以我需要解析它。我可以用一种极其复杂的方式来做到这一点,但似乎必须有更好的方式。
Is this really the best I can do?
这真的是我能做的最好的吗?
HttpResponse response; // some response object
Reader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0) {
builder.append(buf, 0, l);
l = in.read(buf);
}
JSONTokener tokener = new JSONTokener( builder.toString() );
JSONArray finalResult = new JSONArray( tokener );
I'm on Android if that makes any difference.
如果这有什么不同,我在Android上。
采纳答案by BalusC
Two things which can be done more efficiently:
可以更有效地完成两件事:
- Use
StringBuilderinstead ofStringBuffersince it's the faster and younger brother. - Use
BufferedReader#readLine()to read it line by line instead of reading it char by char.
- 使用
StringBuilder而不是StringBuffer因为它是更快的弟弟。 - 用于
BufferedReader#readLine()逐行读取,而不是逐个字符读取。
HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
If the JSON is actually a single line, then you can also remove the loop and builder.
如果 JSON 实际上是一行,那么您还可以删除循环和构建器。
HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
回答by ZZ Coder
Use JSON Simple,
使用简单的 JSON,
http://code.google.com/p/json-simple/
http://code.google.com/p/json-simple/
Which has a small foot-print, no dependencies so it's perfect for Android.
它占用空间小,没有依赖项,因此非常适合 Android。
You can do something like this,
你可以做这样的事情,
Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;
回答by CommonsWare
Hymansonappears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.
Hymanson似乎支持直接从InputStream. 我的理解是它在 Android 上运行并且速度相当快。另一方面,它是一个额外的 JAR 包含在您的应用程序中,增加了下载和闪存大小。
回答by guido
There is no need to do the reader loop yourself. The JsonTokener has this built in. E.g.
没有必要自己做读者循环。JsonTokener 内置了这个。例如
ttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new
JSONTokener tokener = new JSONTokener(reader);
JSONArray finalResult = new JSONArray(tokener);
回答by Jove Kuang
Instead of doing
而不是做
Reader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0) {
builder.append(buf, 0, l);
l = in.read(buf);
}
JSONTokener tokener = new JSONTokener( builder.toString() );
You can do:
你可以做:
JSONTokener tokener = new JSONTokener(
IOUtils.toString(response.getEntity().getContent()) );
where IOUtils is from the commons IO library.
其中 IOUtils 来自公共 IO 库。
回答by Jonathan Lin
For Android, and using Apache's Commons IOLibrary for IOUtils:
对于 Android,使用 Apache 的Commons IO库IOUtils:
// connection is a HttpURLConnection
InputStream inputStream = connection.getInputStream()
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(inputStream, baos);
JSONObject jsonObject = new JSONObject(baos.toString()); // JSONObject is part of Android library
回答by Rajesh Batth
You can use the Gson library for parsing
您可以使用 Gson 库进行解析
void getJson() throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("some url of json");
HttpResponse httpResponse = httpClient.execute(httpGet);
String response = EntityUtils.toString(httpResponse.getEntity());
Gson gson = new Gson();
MyClass myClassObj = gson.fromJson(response, MyClass.class);
}
here is sample json file which is fetchd from server
这是从服务器获取的示例 json 文件
{
"id":5,
"name":"kitkat",
"version":"4.4"
}
here is my class
这是我的班级
class MyClass{
int id;
String name;
String version;
}
refer this
参考这个

