我试图通过GSON将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
}
]
}
我已经搜索了很多东西,但找不到可以帮助解决这个问题的问题,我知道为什么NullPointException会发生但不知道它是如何解决它的。我是看过这个例子 - {3但在这种情况下,它并没有真正帮助我(或者它可能但不确定)。谢谢您的时间:)
答案 0 :(得分:0)
根据您发布的代码,您的数组ArrayList <User> child
为空。当您第一次尝试在此行for (User U : child) {
上访问它时,这将导致NullPointerException。您需要初始化子数组,如ArrayList <User> child = new ArrayList<User>()
。
您的代码还存在许多其他问题。