[英]Reading XML file in JAVA and creating database
I have a problem reading "traits" from an XML file and filling a table in a database.我在从 XML 文件读取“特征”并在数据库中填充表时遇到问题。 I successfully read teacher and student list but I get error trying to read traits.我成功阅读了教师和学生名单,但在尝试阅读特征时出错。 For parsing I am using jackson-dataformat-xml.对于解析,我使用 jackson-dataformat-xml。 Any help would be really appreciated.任何帮助将非常感激。
The error that I am getting:我得到的错误:
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
This is my XML file:这是我的 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() {
}
}
You need to create a Traits
class, which is like this ...你需要创建一个Traits
类,就像这样......
class Traits {
List<Trait> traits
}
The student then has an instance of the Traits
class composed into it.然后,学生将Traits
类的一个实例组合到其中。 This will allow you to deserialize, I think.我认为这将允许您反序列化。
Does this resolve your problem ?这能解决您的问题吗? Let me know in the comments.在评论中告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.