我正在使用以下代码从API获取响应。

BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        System.out.println("bf.readLine() - " + bf.readLine());

        output = bf.readLine();
        while (output != null) {
            JSONObject obj = new JSONObject(output);
            System.out.println("output is " + output);
            resCode = obj.getString("resCode");
            resDesc = obj.getString("COUNT");
        }


我可以返回bf.readLine()响应,如下所示。

{"status":true,"data":[{"COUNT":"0"}]}


问题是当我将bf.readLine()分配给String并检查该值时,它变为null。为什么bf.readLine()显示为null(给出null点异常),即使它从API返回值也是如此。

最佳答案

您的代码应为

BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

String output = null;

        while ((output = bf.readLine()) != null) {
         System.out.println("bf.readLine() value is--- - " + output );

            JSONObject obj = new JSONObject(output);
            System.out.println("output is " + output);
            resCode = obj.getString("resCode");
            resDesc = obj.getString("COUNT");
        }

关于java - Java BufferedReader值变为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37850691/

10-10 06:22