反序列化Gson NullPointer?

时间:2015-09-04 05:19:08

标签: java json gson

我正在尝试解析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)

2 个答案:

答案 0 :(得分:1)

我正在回答我自己的问题。

JSON区分大小写,因此在("ROLE_Student") gson找不到任何值。相反,我用("ROLE_student")更正了它并且它有效。

感谢@Tobia Tesan

答案 1 :(得分:0)

更改此行

Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();

Boolean isStudent = roles.get("ROLE_student").getAsBoolean();