在解析JSON时接收Null

时间:2018-06-01 09:31:35

标签: 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"));
    }
}

有人能看出为什么我会得到一个空指针吗?

1 个答案:

答案 0 :(得分: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");
            }
        }
    }