以下是我通过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"));
}
}
有人能看出为什么我会得到一个空指针吗?
答案 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");
}
}
}