简体   繁体   English

解析JSON时接收Null

[英]Receiving Null while Parsing JSON

Here is the response that I am receiving from my REST service from a GET Request: 这是我从REST服务收到的来自GET请求的响应:

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

I am trying to retrieve the userPin value from the JSON. 我正在尝试从JSON检索userPin值。

Here is the code I have attempted: 这是我尝试的代码:

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

Can anyone see why I am getting a Null Pointer? 谁能看到我为什么得到空指针?

I have not tested this one yet. 我还没有测试过 But I think the problem is userPin is string not an integer value. 但我认为问题在于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");
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM