Java 备忘: Jackson 包的 XML 注解支持
2017-08-24 本文已影响1030人
字母数字或汉字
官方文档 https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations 还是有点晦涩的,本文提供注解与其对应的 XML 的预览,便于理解。
典型 XML 如下
<root k6="6">
<k1>str</k1>
<k-2>2</k-2>
<k3>
<ki>1</ki>
<ki>2</ki>
</k3>
<k4>
<ka>3</ka>
<ka>4</ka>
</k4>
<k5>5-1</k5>
<k5>5-2</k5>
<k7>a7b</k7>
<k8><a>8</a></k8>
<k9><![CDATA[中<a>文]]></k9>
</root>
对应于带 Jackson 注解的 JavaBean 如下
import java.util.*;
import com.fasterxml.jackson.dataformat.xml.annotation.*;
import lombok.Data;
@Data
@JacksonXmlRootElement(localName = "root")
public class RootXml {
private String k1;
@JacksonXmlProperty(localName = "k-2")
private Integer k2;
@JacksonXmlElementWrapper(localName = "k3")
private Collection<String> ki;
@JacksonXmlElementWrapper(localName = "k4")
@JacksonXmlProperty(localName = "ka")
private Collection<String> k4;
@JacksonXmlElementWrapper(localName = "k5", useWrapping = false)
private Collection<String> k5;
@JacksonXmlProperty(isAttribute = true)
private Integer k6;
@Data
public static class Value1 {
@JacksonXmlText
private String a;
}
private Value1 k7;
@Data
public static class Value2 {
@JacksonXmlText(value = false)
private String a;
}
private Value2 k8;
@JacksonXmlCData(value = true) // 序列化时是否总是使用 CDATA 块
private String k9;
}