以下是我通过 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/