我想通過GSON解析JSON代碼到JAVA。我以前提出過類似的例子,它完美地工作,但是當我嘗試在我的程序來實現它給人的錯誤:異常在線程「主」java.lang.NullPointerException - JSon到Java
'Exception in thread "main" java.lang.NullPointerException
at personality.Child.toString(Child.java:25)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at personality.Personality.main(Personality.java:48)
' 很堅持這一點,我已經做了研究,但仍無法找到清晰的解決方所以我在問你們。
我的代碼:
人格主類
public class Personality {
public static void main(String[] args) throws IOException {
// TODO code application logic her
Gson gson = new Gson();
Child C = gson.fromJson(new FileReader("user.json"), Child.class);
System.out.println(C);
}
}
用戶類別
public class User {
public String category;
public String id;
public String name;
public double percentage;
public double sampling_error;
//Constructor
public User(String category, String id, String name , double percentage, double sampling_error) {
this.category = category;
this.id = id;
this.name = name;
this.percentage = percentage;
this.sampling_error = sampling_error;
}
@Override
public String toString() {
return "Category " + category + " : id = " + id + " name = " + name;
}
}
子類
public class Child {
public ArrayList <User> child; //Assign arraylist User to Child class
// toString override - not related to JSON processing, just included for debugging purposes
@Override
public String toString() {
StringBuilder A = new StringBuilder();
A.append("Number of childrens = " + child.size() + "\n"); //Error points to here
for (User U : child) {
A.append(U.toString() + "\n"); //assigns Planet To string to
}
return A.toString();
}
的Json代碼
{
"children": [
{
"category": "personality",
"id": "Adventurousness",
"name": "Adventurousness",
"percentage": 0.7871810497070462,
"sampling_error": 0.0535169534
},
{
"category": "personality",
"id": "Emotionality",
"name": "Emotionality",
"percentage": 0.9806198117683198,
"sampling_error": 0.0500385256
},
{
"category": "personality",
"id": "Liberalism",
"name": "Authority-challenging",
"percentage": 0.9958295966962101,
"sampling_error": 0.08735455339999999
}
]
}
我已經搜索很多東西,但無法找到的問題,可以幫助是解決這個問題,我knid知道爲什麼NullPointException發生,但不知道它是如何解決it.And是的,我看過這個例子 - What is a NullPointerException, and how do I fix it?,但在這方面並沒有真正幫助我(或者可能但不確定)。謝謝你的時間:)
'Child'類中的'child'字段名稱不適合它,因爲'child'的類型是User'null'。而NullPointerException。所以,我認爲你的映射有問題。我在'Child'類中看不到'children'字段。 – davidxxx