9

我正在使用 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"

这是可以理解的,但我想知道是否有办法让它与杰克逊 XML 一起工作?

4

2 回答 2

8

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;
   }
}
于 2013-05-08T14:06:37.857 回答
4

虽然这是一篇旧文章,但我刚刚遇到了这个问题,匹配我的服务调用所需的 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>
于 2021-03-31T13:13:02.133 回答