我在测试类中读取我的JSON文件时遇到此错误,看它是否有效,我不明白为什么。它已经过验证,因此JSON文件没有任何问题。任何帮助将不胜感激。
我的考试班:
public class ObjectToJsonFile {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
File file = new File("question.json");
try {
// Deserialize JSON file into Java object.
Question question= mapper.readValue(file, Question.class);
System.out.println("category.getCategory() = " + question.getCategory());
} catch (IOException e) {
e.printStackTrace();
}
}
我的答案类看起来像这样:
public class Answer
{
@JsonProperty("answer")
private String answer;
@JsonProperty("correct")
private Boolean correct;
//setters and getters
}
我的问题类看起来像这样:public class Question {
@JsonProperty("category")
private String category;
@JsonProperty("clue")
private String clue;
@JsonProperty("Answers")
private List<Answer> answers;
@JsonProperty("questionTitle")
private String questionTitle;
//setters an getters
}
我的问题类:
public class Questions {
@JsonProperty("Questions")
private List<Questions> questions;
@JsonCreator
public Questions(List<Questions> questions) {
super();
this.questions = questions;
}
// setters and getters
}
你有很多小错误。在Questions
中缺少注释,错误的字段名称或混淆Question
与main()
类型。我或多或少地修改了下面的代码,请参阅以下代码中的注释:
回答:
public class Answer {
@JsonProperty("answer")
private String answer;
@JsonProperty("Correct") // was "correct"
private Boolean correct;
问题:
public class Questions {
@JsonProperty("Questions")
private List<Question> questions;
@JsonCreator
public Questions(@JsonProperty("Questions") List<Question> questions) { // was missing @JsonProperty
this.questions = questions;
}
主要:
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
File file = new File("question.json");
try {
Questions question = mapper.readValue(file, Questions.class); // was Question
System.out.println("category.getCategory() = " + question.getQuestions().get(0).getCategory()); // corrected after changing to Questions
} catch (IOException e) {
e.printStackTrace();
}
}
在编写用于映射json数组的java类时,要非常小心并验证将通过setter方法注入的每个字段。您的问题在于以下代码。你做的只是一个小错误。
@JsonProperty("Questions")
private List<Question> questions;//it should be Question object
@JsonCreator
public Questions(List<Question> questions)//change the constructor accordingly
如果您仍然遇到问题,只需检查所有可能的注射是否正确。
祝好运!