当使用Jackson进行JSON处理时,我扩展了JsonDeserializer<T>
并能够处理自定义反序列化。使用Jackson处理XML有类似的事情吗?
import java.util.List;
public class Something {
private int iinteger;
private String sstring;
private List<String> sarray;
public Something(int iinteger, String sstring, List<String> sarray) {
this.iinteger = iinteger;
this.sstring = sstring;
this.sarray = sarray;
}
public Shit() {
}
public int getIinteger() {
return iinteger;
}
public void setIinteger(int iinteger) {
this.iinteger = iinteger;
}
public String getSstring() {
return sstring;
}
public void setSstring(String sstring) {
this.sstring = sstring;
}
public List<String> getSarray() {
return sarray;
}
public void setSarray(List<String> dumb) {
this.sarray = dumb;
}
}
我想从
反序列化<?xml version="1.0"?>
<Something xmlns="">
<iinteger>23</iinteger>
<sstring>hey</sstring>
<sarray >abc abd abv</sarray >
</Something>
答案 0 :(得分:6)
除了JSON,Jackson还de/serializes from/to XML。
您需要以下依赖项:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.6.3</version>
</dependency>
除了standard Jackson annotations和可选的JAXB annotations(javax.xml.bind.annotation
)之外,杰克逊提供了一些XML-specific annotations。
以下面的POJO为例:
public class Simple {
public int x = 1;
public int y = 2;
}
您可以使用以下命令将其序列化为XML:
ObjectMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(new Simple());
结果是:
<Simple>
<x>1</x>
<y>2</y>
</Simple>
要反序列化:
ObjectMapper xmlMapper = new XmlMapper();
Simple value = xmlMapper.readValue("<Simple><x>1</x><y>2</y></Simple>", Simple.class);
答案 1 :(得分:2)