Java 如何使用 FasterXML 反序列化带有注释的 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23632419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to deserialize XML with annotations using FasterXML
提问by sbenderli
I have the following XML schema:
我有以下 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>
I need to convert this into POJO as:
我需要将其转换为 POJO:
public class Schedule
{
public int semester;
public Course[] courses;
}
public class Course
{
public String code;
public int credits;
public String name;
}
There are two important things to note here:
这里有两件重要的事情需要注意:
- The courses object are not wrapped in a tag
- Some of the properties are attributes
- 课程对象未包装在标签中
- 一些属性是属性
How do I need to annotate my objects to get FasterXML to deserialize this xml?
我需要如何注释我的对象才能让 FasterXML 反序列化这个 xml?
回答by Micha? Ziober
You have to add Hymanson-dataformat-xml
dependency to your project:
您必须向Hymanson-dataformat-xml
项目添加依赖项:
<dependency>
<groupId>com.fasterxml.Hymanson.dataformat</groupId>
<artifactId>Hymanson-dataformat-xml</artifactId>
<version>2.3.3</version>
</dependency>
After that you can use XML annotations in this way:
之后,您可以以这种方式使用 XML 注释:
@HymansonXmlRootElement(localName = "Courses")
class Schedule {
@HymansonXmlProperty(isAttribute = true)
private int semester;
@HymansonXmlProperty(localName = "Course")
private Course[] courses;
// getters, setters, toString, etc
}
class Course {
@HymansonXmlProperty(isAttribute = true)
private String code;
@HymansonXmlProperty(isAttribute = true)
private int credits;
@HymansonXmlText(value = true)
private String name;
// getters, setters, toString, etc
}
Now, you have to use XmlMapper
instead of ObjectMapper
:
现在,您必须使用XmlMapper
代替ObjectMapper
:
HymansonXmlModule module = new HymansonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper(module);
System.out.println(xmlMapper.readValue(xml, Schedule.class));
Above script prints:
以上脚本打印:
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]]]