微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Jackson XML映射器将Java List序列化为XML

嗨,我需要使用Jackson-dataformat XMLMapper从JAVA创建XML.
XML应该是这样的
<Customer>
  <id>1</id>
  <name>Mighty Pulpo</name>
    <addresses>
      <city>austin</city>
      <state>TX</state>
    </addresses>
    <addresses>
      <city>Hong Kong</city>
      <state>Hong Kong</state>
    </addresses>
</Customer>

但我总是喜欢额外的“< addresses>< / addresses>”标签.

<Customer>
  <id>1</id>
  <name>Mighty Pulpo</name>
<addresses>
    <addresses>
      <city>austin</city>
      <state>TX</state>
    </addresses>
    <addresses>
      <city>Hong Kong</city>
      <state>Hong Kong</state>
    </addresses>
<addresses>
</Customer>

我使用下面的代码创建XML

JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
XmlMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(jaxbAnnotationModule);
mapper.registerModule(new GuavaModule());
String xml = mapper.writeValueAsstring(customer);
System.out.println(xml);

有人可以帮帮我吗?如何删除额外的标签呢.我曾尝试使用@XmlElement,但它没有帮助. TIA!

请尝试以下代码
@JacksonXmlRootElement(localName = "customer") 
class Customer {

    @JacksonXmlProperty(localName = "id")
    private int id;
    @JacksonXmlProperty(localName = "name")
    private String  name;

    @JacksonXmlProperty(localName = "addresses")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Address[] address;

    //getters,setters,toString
}

class Address {

    @JacksonXmlProperty(localName = "city")
    private String city;

    @JacksonXmlProperty(localName = "state")
    private String state;
    // getter/setter 
}

原文地址:https://www.jb51.cc/xml/293046.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。