解析时收到 Null JSON
Receiving Null while Parsing JSON
这是我通过 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");
}
}
}
这是我通过 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");
}
}
}