即使在使用少量变体后,也无法从输入流中读取大型JSON请求数据

时间:2016-03-13 14:39:31

标签: java json

我正在使用post man发送JSon请求。然后我使用getInputStream()获取inputStream。

    InputStream inputStream = request.getInputStream();

我有一个2032字符的JSon请求,它可能会根据场景增加。我尝试了类似问题的一些建议,但使用所有我只能读取1011字符。

以下是我尝试过的方法。

声明:

    BufferedReader bufferedReader = null;
    StringBuilder stringBuilder = new StringBuilder();
    // stringBuilder.ensureCapacity(1048576);
    JSONObject jObj = null;
    InputStream inputStream = request.getInputStream();

1)

        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[1048576];
        int bytesRead = -1;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }

2)

        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();

3)

        String line;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

4)

        stringBuilder.ensureCapacity(1048576);
        BoundedInputStream boundedInputStream = new BoundedInputStream(inputStream);
        bufferedReader = new BufferedReader(new InputStreamReader(boundedInputStream, "UTF-8"));

        // StringBuilder builder= new StringBuilder();
        StringBuilderWriter bufferedwriter = new StringBuilderWriter(stringBuilder);
        IOUtils.copy(bufferedReader, bufferedwriter);

5)

         bufferedReader = request.getReader();
         char[] charBuffer = new char[1048576];
         int bytesRead = -1;
         while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
         stringBuilder.append(charBuffer, 0, bytesRead);
         }

最终消费:使用第二个变化结果是我最近的尝试

            // jObj = new JSONObject(stringBuilder.toString());
            // jObj = new JSONObject(bufferedwriter.toString());
            jObj = new JSONObject(result.toString());

注意:我只是通过将char容量增加到1048576来验证是否可以解决问题。但增加这一点对输入流也没有影响。

有人可以告诉我如何阅读大型Json输入。如果我做错了,请告诉我。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您似乎想将JSON转换为var timer = NSTimer() @IBAction func stop(sender: AnyObject) { timer.invalidate() timer = nil 。使用Java 8,这变得有点简单。

String

说明:

  1. 从输入流创建 // (1) try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { // (2) String json = reader.lines().collect(Collectors.joining("\n")); // do something with `json`... } 。使用“try-with-resources”意味着,当离开BufferedReader块时,阅读器将自动关闭。
  2. try {}有一个方法BufferedReader,返回lines()。您可以使用Stream<String>收集器加入所有String