反序列化 Gson NullPointer?
Deserializing Gson NullPointer?
我正在尝试解析 JSON 以获得一些值。
{
"username":"shobhit@gmail.com",
"roles:
{
"ROLE_Student_Trial":true,
"ROLE_student":true,
"ROLE_Student_Unlimited":true
},
"type":"student",
"lastLogin":1441305986000,
"token":"123"
}
这就是我反序列化它的方式
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
String userName = obj.get("username").getAsString();
JsonObject roles = obj.get("roles").getAsJsonObject();
Boolean isTrial = roles.get("ROLE_Student_Trial").getAsBoolean();
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
Boolean isUnlimited = roles.get("ROLE_Student_Unlimited").getAsBoolean(); // LoginTest.java:31
long lastLogin = obj.get("lastLogin").getAsLong();
int token = obj.get("token").getAsInt();
String type = obj.get("type").getAsString();
System.out.println(userName);
if(isTrial){
System.out.println("Student trial is on last login " + timeConverter(lastLogin));
}
if(isStudent){
System.out.println("Student access level");
}
if(isUnlimited){
System.out.println("Student is unlimited as " + type + " and its token = " + token);
}
我试图获取内部 JSON 的值,
但我收到 NullPointerException。
Exception in thread "main" java.lang.NullPointerException
at loginActivityHttpURL.LoginTest.main(LoginTest.java:31)
更改此行
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
至
Boolean isStudent = roles.get("ROLE_student").getAsBoolean();
我正在回答我自己的问题。
JSON 区分大小写,因此在 ("ROLE_Student")
gson 找不到任何值。相反,我用 ("ROLE_student")
更正了它并且它起作用了。
感谢@Tobia Tesan
我正在尝试解析 JSON 以获得一些值。
{
"username":"shobhit@gmail.com",
"roles:
{
"ROLE_Student_Trial":true,
"ROLE_student":true,
"ROLE_Student_Unlimited":true
},
"type":"student",
"lastLogin":1441305986000,
"token":"123"
}
这就是我反序列化它的方式
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
String userName = obj.get("username").getAsString();
JsonObject roles = obj.get("roles").getAsJsonObject();
Boolean isTrial = roles.get("ROLE_Student_Trial").getAsBoolean();
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
Boolean isUnlimited = roles.get("ROLE_Student_Unlimited").getAsBoolean(); // LoginTest.java:31
long lastLogin = obj.get("lastLogin").getAsLong();
int token = obj.get("token").getAsInt();
String type = obj.get("type").getAsString();
System.out.println(userName);
if(isTrial){
System.out.println("Student trial is on last login " + timeConverter(lastLogin));
}
if(isStudent){
System.out.println("Student access level");
}
if(isUnlimited){
System.out.println("Student is unlimited as " + type + " and its token = " + token);
}
我试图获取内部 JSON 的值, 但我收到 NullPointerException。
Exception in thread "main" java.lang.NullPointerException
at loginActivityHttpURL.LoginTest.main(LoginTest.java:31)
更改此行
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
至
Boolean isStudent = roles.get("ROLE_student").getAsBoolean();
我正在回答我自己的问题。
JSON 区分大小写,因此在 ("ROLE_Student")
gson 找不到任何值。相反,我用 ("ROLE_student")
更正了它并且它起作用了。
感谢@Tobia Tesan