java - 解析 JSON 时接收 Null

标签 java android json parsing httpresponse

以下是我通过 GET 请求从 REST 服务收到的响应:

{
  "type": "usersTable",
  "employeeId": 1,
  "employeeName": "Andrew Watson",
  "userPin": "705207"
}

我正在尝试从 JSON 中检索 userPin 值。

这是我尝试过的代码:

if (con.getResponseCode() == HttpsURLConnection.HTTP_OK 
           || con.getResponseCode() == HttpsURLConnection.HTTP_ACCEPTED ) {
    String line;
    BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
    while ((line=br.readLine()) != null) {
        JSONObject json = new JSONObject(br.toString());
        userPinRetrieved = String.valueOf(json.getInt("userPin"));
    }
}

有人能明白为什么我得到一个空指针吗?

最佳答案

我还没有测试过这个。但我认为问题是 userPin 是字符串而不是整数值。

 if (con.getResponseCode() == HttpsURLConnection.HTTP_OK 
               || con.getResponseCode() == HttpsURLConnection.HTTP_ACCEPTED ) {
        String line;
        BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
        while ((line=br.readLine()) != null) {
            JSONObject json = new JSONObject(br.toString()); 
            if(json.getString("userPin") == null) {
               //do something here or define the default value
            }else {
                userPinRetrieved = json.getString("userPin");
            }
        }
    }

关于java - 解析 JSON 时接收 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50640327/

相关文章:

Java 文件传输 API

javascript - angularjs UI-Router 不路由 .jsp View

android - 当隐藏状态栏时,有没有办法阻止 "jumping"的布局?

javascript - 将 json HashMap 加载到 javascript 对象中

javascript - 如何将字符串转换为对象属性?

java - RTF Java 解析器

java - 单击按钮时如何更改背景颜色

java - 禁用按钮一段时间

Android Gradle - 检查正在执行哪个任务

javascript - 如何从数组中保存在某个位置的 JSON 行访问属性?