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

前端之家收集整理的这篇文章主要介绍了使用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 
}

猜你在找的XML相关文章