我正在使用Jackson XML插件(https://github.com/FasterXML/jackson-dataformat-xml),我不确定它是否受支持,但我想知道是否可以使用命名空间前缀序列化和反序列化XML,如此:
<name:Foo>
<name:Bar>
<name:x>x</name:x>
<name:y>y</name:y>
</name:Bar>
</name:Foo>
我可以使用Jackson的插件生成这种类型的XML,如下所示:
@JacksonXmlProperty(localName="name:Bar")
public Bar getBar() {
return bar;
}
但是,我找不到一种方法来配置我的POJO以从生成的XML反序列化。请参阅以下示例代码:
public class Bar{
@JacksonXmlProperty(localName="name:x")
public String x = "x";
@JacksonXmlProperty(localName="name:y")
public String y = "y";
}
@JacksonXmlRootElement(localName="name:Foo")
public class Foo{
private Bar bar;
@JacksonXmlProperty(localName="name:Bar")
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
public class TestDeserialization {
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
foo.setBar(new Bar());
XmlMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(foo);
System.out.println(xml);
System.out.println("XML Desearialzing....");
Foo foo2= xmlMapper.readValue(xml, Foo.class);
System.out.println(xmlMapper.writeValueAsString(foo2));
}
}
尝试运行此测试会给我一个例外:
Exception in thread "main" java.io.IOException: com.ctc.wstx.exc.WstxParsingException: Undeclared namespace prefix "name"
这是可以理解的,但我想知道是否有办法让它与Jackson XML一起使用?
答案 0 :(得分:3)
JacksonXmlProperty
注释具有属性namespace
。用它来定义namespace
public class Bar {
@JacksonXmlProperty(namespace = "name",localName="x")
public String x = "x";
@JacksonXmlProperty(namespace = "name",localName="y")
public String y = "y";
}
@JacksonXmlRootElement(namespace = "name", localName = "Foo")
public class Foo {
private Bar bar;
@JacksonXmlProperty(namespace = "name", localName = "Bar")
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
答案 1 :(得分:1)
虽然这是一篇旧帖子,但我刚刚遇到了这个问题,匹配我的服务调用所需的 XML 的唯一解决方案是这样的,其中命名空间声明也使用前缀。
@JacksonXmlRootElement(localName = "entry")
abstract class BaseEntry implements Serializable {
private static final long serialVersionUID = 6835429382441010779L;
private final String xmlns = "com.foo.bar";
private String type;
protected BaseEntry(String type) {
this.type = type;
}
@JacksonXmlProperty(isAttribute = true)
public String getType() {
return type;
}
@JacksonXmlProperty(localName = "xmlns:ns2", isAttribute = true)
public String getXmlns() {
return xmlns;
}
}
这会产生类似的结果:
<entry type="com.foo.bar" xmlns:ns2="com.foo.bar">
...
</entry>