【问题标题】:Receiving Null while Parsing JSON解析 JSON 时接收 Null
【发布时间】:2018-06-01 09:31:34
【问题描述】:

这是我从 REST 服务收到的来自 GET 请求的响应:

{
  "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"));
    }
}

谁能明白为什么我得到一个空指针?

【问题讨论】:

  • 你能和我们分享一下错误日志吗?
  • 为什么是br.toString()
  • @Lokesh 我在本网站的其他示例中看到过这种方式。我应该使用其他方式吗?
  • 请完整的崩溃日志。
  • json.getInt 在字符串上?您的 userPin 是 String 而不是 int。

标签: java android json parsing httpresponse


【解决方案1】:

我还没有测试过这个。但我认为问题在于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");
            }
        }
    }

【讨论】:

  • 在运行时接收到 null 但在调试时接收到正确的值,这很奇怪吗? @Lokesh
  • 你能检查你的对象的属性“userPin”是否有pin值吗?
  • @AndroidBeginner2018 我已经更新了我的答案。您可以为 userPinRetrieved 定义一个默认值或执行其他操作(如果它为 null)。这次不应该抛出异常
  • 是的,它在调试模式下获得了正确的引脚值。虽然当我实际运行程序时它变得空了。很奇怪。
  • @AndroidBeginner2018 你能试试更新的答案吗?您能否包含代码,为什么它会变为 null ?我认为您收到的数据具有空值。如果是这种情况,那么您可以使用更新的答案来避免它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多