如何使用FasterXML使用注释反序列化XML [英] How to deserialize XML with annotations using FasterXML
本文介绍了如何使用FasterXML使用注释反序列化XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下XML架构:
<Courses semester="1">
<Course code="A231" credits="3">Intermediate A</Course>
<Course code="A105" credits="2">Intro to A</Course>
<Course code="B358" credits="4">Advanced B</Course>
</Courses>
我需要将其转换为POJO:
I need to convert this into POJO as:
public class Schedule
{
public int semester;
public Course[] courses;
}
public class Course
{
public String code;
public int credits;
public String name;
}
这里有两点需要注意:
- 课程对象未包含在标签中
- 某些属性属性
我如何需要注释我的对象才能让FasterXML反序列化这个xml?
How do I need to annotate my objects to get FasterXML to deserialize this xml?
推荐答案
您必须将 jackson-dataformat-xml
依赖项添加到您的项目:
You have to add jackson-dataformat-xml
dependency to your project:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.3.3</version>
</dependency>
之后你可以用这种方式使用XML注释:
After that you can use XML annotations in this way:
@JacksonXmlRootElement(localName = "Courses")
class Schedule {
@JacksonXmlProperty(isAttribute = true)
private int semester;
@JacksonXmlProperty(localName = "Course")
private Course[] courses;
// getters, setters, toString, etc
}
class Course {
@JacksonXmlProperty(isAttribute = true)
private String code;
@JacksonXmlProperty(isAttribute = true)
private int credits;
@JacksonXmlText(value = true)
private String name;
// getters, setters, toString, etc
}
现在,您必须使用 XmlMapper
而不是 ObjectMapper
:
Now, you have to use XmlMapper
instead of ObjectMapper
:
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper(module);
System.out.println(xmlMapper.readValue(xml, Schedule.class));
以上脚本打印:
Schedule [semester=1, courses=[[code=A231, credits=3, name=Intermediate A], [code=A105, credits=2, name=Intro to A], [code=B358, credits=4, name=Advanced B]]]
这篇关于如何使用FasterXML使用注释反序列化XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文