我有以下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为:
public class Schedule
{
public int semester;
public Course[] courses;
}
public class Course
{
public String code;
public int credits;
public String name;
}
这里有两件重要的事情需要注意:
- courses对象没有被包装在标签 中
- 有些属性是属性
我需要如何注释我的对象来获得FasterXML来反序列化这个xml?
您必须将jackson-dataformat-xml
依赖项添加到您的项目中:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.3.3</version>
</dependency>
之后,您可以这样使用XML注释:
@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
:
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]]]