Serializing a Java List in XML with Jackson XML Adapter

Hey. I need to create XML from JAVA using XMLMapper using Jackson-dataformat. XML should look 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 always get it with the optional tag "<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> 

I use 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 help me? How can I remove the extra tag, please. I tried using @XmlElement, but that will not help. TIA !!

+8
java xml jackson pojo
source share
3 answers

Try the code below

 @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 } 
+20
source share

This parameter changes the default wrapping behavior if you do not want to use annotation throughout your code.

 XmlMapper mapper = new XmlMapper(); mapper.setDefaultUseWrapper(false); 
+1
source share

Just add ManojP's answer, if adding @JacksonXmlElementWrapper(useWrapping = false) to the declaration of your variable does not work (which was for me), adding it to the getter method will do the trick.

0
source share

All Articles