我想解析JSON來獲取一些值。反序列化Gson NullPointer?
{
"username":"[email protected]",
"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)
哪一行是LoginTest.java:31? – KDM
@Pythonian,你*知道JSON是區分大小寫的,對嗎?我在那裏看到一個「學生」代替「學生」 –
@TobiaTesan哦謝謝,不,我不知道,我是JSON和GSON的新手。這就是問題! – Omkar