简体   繁体   中英

Serialize Java List to XML using Jackson XML mapper

Hi I need to create an XML from JAVA using Jackson-dataformat XMLMapper. The XML should be like

<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>

But I get it always like with an extra "< addresses> < /addresses>" tag.

<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>

I am using below code to create 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);

Please can some one help me? How can I remove the extra tag please. I have tried to use @XmlElement but it does not help help. TIA!!

Try the below code

@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 
}

This setting changes default wrapping behavior, if you don't want to deal with annotation everywhere in your code.

XmlMapper mapper = new XmlMapper();
mapper.setDefaultUseWrapper(false);

只是为了添加ManojP的答案,如果在变量声明中添加@JacksonXmlElementWrapper(useWrapping = false)不起作用(对我来说就是这种情况),将它添加到getter方法就可以了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM