【发布时间】:2021-12-23 00:44:09
【问题描述】:
我在从 XML 文件中读取“特征”并在数据库中填充表时遇到问题。我成功阅读了教师和学生名单,但尝试阅读特征时出错。对于解析,我使用的是 jackson-dataformat-xml。任何帮助将不胜感激。
我得到的错误:
JSON parse error: Cannot deserialize value of type `java.util.ArrayList<com.Homework.Structure.Trait>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<com.Better.Homework.Structure.Trait>` from Object value (token `JsonToken.START_OBJECT`)\n
这是我的 XML 文件:
<teacher id="100" class="English">
<students>
<student>
<id>1</id>
<first_name>Alice</first_name>
<last_name>Wild</last_name>
<traits>
<trait>nice</trait>
<trait>good_grades</trait>
</traits>
</student>
<student>
<id>2</id>
<first_name>John</first_name>
<last_name>Doe</last_name>
<traits>
<trait>kind</trait>
<trait>likes_to_help</trait>
</traits>
</student>
</students>
</teacher>
@Data
@Entity
@Table
public class Teacher{
@SequenceGenerator(
name = "teacher_sequence",
sequenceName = "teacher_sequence",
allocationSize = 1
)
@JacksonXmlProperty(isAttribute = true, localName="id") private Integer id;
@JacksonXmlProperty(isAttribute = true, localName = "class") private String class;
@OneToMany (cascade = CascadeType.ALL)
private List<Student> students;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Data
@Entity
@Table
public class Student{
@SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
@Id
private Integer id;
private String first_name;
private String last_name;
@OneToMany (cascade = CascadeType.ALL)
private List <Trait> traits;
// @ElementCollection
// private List <String> traits;
}
@Table
@Data
@Entity
public class Trait {
@SequenceGenerator(
name = "trait_sequence",
sequenceName = "trait_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "trait_sequence"
)
@Id
private String traits;
// @JsonCreator
// public Trait(@JsonProperty("traits") String trait) {
// this.trait = trait;
// }
public Trait() {
}
}
【问题讨论】:
-
病人课在哪里?
-
我刚刚编辑过,由于隐私原因不想发布确切的原始代码,所以我更改了类名和xml属性。感谢您的评论。
-
您对 XML 文档有 JSON 解析错误?听起来很奇怪……
-
我猜杰克逊在抱怨,因为
<traits>是一个包含<trait>的序列,而你的Trait类有一个名为traits的属性,因此它不能将<trait>映射到@ 987654331@。顺便说一句,如果是我的代码,我将创建不可变类来表示接收到的入站 XML,并为数据库实体创建单独的类,从而分离这两个问题。
标签: java xml database parsing jackson