我要转换的 xml 文件如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<question id="1">
<answer>
<answername>java is a programming language</answername>
<id>101</id>
<postedby>ravi</postedby>
</answer>
<answer>
<answername>java is a platform</answername>
<id>102</id>
<postedby>john</postedby>
</answer>
<questionname>What is java?</questionname>
</question>
我试图将文件转换为的对象如下:
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Question {
private int id;
private ArrayList<Answer> answers;
private String questionname;
public Question() {
}
public Question(int id, ArrayList<Answer> answers, String questionname) {
this.id = id;
this.answers = answers;
this.questionname = questionname;
}
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ArrayList<Answer> getAnswers() {
return answers;
}
public void setAnswers(ArrayList<Answer> answers) {
this.answers = answers;
}
public String getQuestionname() {
return questionname;
}
public void setQuestionname(String questionname) {
this.questionname = questionname;
}
}
Answer对象的类如下:
public class Answer {
private int id;
private String answername;
private String postedby;
public Answer() {
}
public Answer(int id, String answername, String postedby) {
this.id = id;
this.answername = answername;
this.postedby = postedby;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswername() {
return answername;
}
public void setAnswername(String answername) {
this.answername = answername;
}
public String getPostedby() {
return postedby;
}
public void setPostedby(String postedby) {
this.postedby = postedby;
}
}
为了进行转换,我创建了以下类:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class App {
public static void main(String[] args) {
File file = new File("question.xml");
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Question question = (Question) jaxbUnmarshaller.unmarshal(file);
System.out.println(question.getAnswers().get(0).getAnswername());
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
当我运行 main 方法时,遇到以下异常:
App.main(App.java:17) 的线程“主”java.lang.NullPointerException 中的异常
第17行指的是:System.out.println(question.getAnswers().get(0).getAnswername());
总结和咨询: 我从以下教程中获取了我的代码:[在此处输入链接描述][1]。我遵循了所有步骤,没有跳过任何内容,所以我认为代码中没有错误。我为我的项目使用的 IDE 是带有 JavaSE-1.8 的 Eclipse Photon。我没有明确导入任何库,也没有使用 Maven。Eclipse 识别注释没有问题。所以我想知道怎么了。谁能帮我弄清楚?[1]:https://www.youtube.com/watch?v=jB_3r_Cz9Ro&t=812s