如何从Java HTTPResponse中解析JSON ?

时间:2020-12-16 20:24:16

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.

我用的是安卓系统,如果有区别的话。

7 个解决方案

#1


82  

Two things which can be done more efficiently:

有两件事可以做得更有效率:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. 使用StringBuilder而不是StringBuffer,因为它是更快更小的。
  3. Use BufferedReader#readLine() to read it line by line instead of reading it char by char.
  4. 使用BufferedReader#readLine()来逐行读取它,而不是通过char读取它。

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

#2


8  

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;

#3


4  

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

请参考这个

#4


1  

Jackson appears 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.

Jackson似乎支持直接从InputStream进行一些JSON解析。我的理解是,它运行在Android系统上,运行速度很快。另一方面,它是一个额外的JAR,包括你的应用,增加下载和flash大小。

#5


0  

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来自commons IO库。

#6


0  

For Android, and using Apache's Commons IO Library 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

#7


-3  

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

#1


82  

Two things which can be done more efficiently:

有两件事可以做得更有效率:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. 使用StringBuilder而不是StringBuffer,因为它是更快更小的。
  3. Use BufferedReader#readLine() to read it line by line instead of reading it char by char.
  4. 使用BufferedReader#readLine()来逐行读取它,而不是通过char读取它。

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

#2


8  

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;

#3


4  

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

请参考这个

#4


1  

Jackson appears 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.

Jackson似乎支持直接从InputStream进行一些JSON解析。我的理解是,它运行在Android系统上,运行速度很快。另一方面,它是一个额外的JAR,包括你的应用,增加下载和flash大小。

#5


0  

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来自commons IO库。

#6


0  

For Android, and using Apache's Commons IO Library 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

#7


-3  

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