问题
I'm working with the Jackson XML plugin (https://github.com/FasterXML/jackson-dataformat-xml), and I'm not sure if it's supported, but I'm wondering if it's possible to both serialize and deserialize XML with namespace prefixes, like so:
<name:Foo>
<name:Bar>
<name:x>x</name:x>
<name:y>y</name:y>
</name:Bar>
</name:Foo>
I can generate this type of XML using Jackson's plugin like so:
@JacksonXmlProperty(localName="name:Bar")
public Bar getBar() {
return bar;
}
However, I can't find a way to configure my POJOs to deserialize from the XML generated. Please see the following example code:
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));
}
}
Trying to run this test gives me an exception:
Exception in thread "main" java.io.IOException: com.ctc.wstx.exc.WstxParsingException: Undeclared namespace prefix "name"
which is understandable, but I was wondering if there's a way to get this to work with Jackson XML?
回答1:
JacksonXmlProperty
annotation has property namespace
. Use it for defining 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;
}
}
来源:https://stackoverflow.com/questions/16442805/jackson-xml-deserializing-xml-with-namespace-prefixes