gpt4 book ai didi

java - 线程 "main"java.lang.NullPointerException 中的异常 - Json 到 Java

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:52 25 4
gpt4 key购买 nike

我正在尝试通过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,但不知道它是如何解决的。是的,我看过这个例子 - What is a NullPointerException, and how do I fix it?但在这种情况下并没有真正帮助我(或者它可能可以但我不确定)。谢谢您的宝贵时间:)

最佳答案

根据您发布的代码,您的数组 ArrayList <User> child一片空白。当您第一次尝试在此行 for (User U : child) { 访问它时,这将导致 NullPointerException 。您需要初始化子数组,例如 ArrayList <User> child = new ArrayList<User>() 。您的代码还存在许多其他问题。

关于java - 线程 "main"java.lang.NullPointerException 中的异常 - Json 到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com