Duplicated field in generated XML using JAXB
This might be quite old, but its the first result while searching for "JAXB duplicate fields"
Stumbled upon the same problem, this did the trick for me:
@XmlRootElement@XmlAccessorType(XmlAccessType.NONE) // <-- made the differencepublic abstract class ParentClass{...}@XmlRootElementpublic class ChildClass extends ParentClass{ ...}
You could use the following approach of marking the property @XmlTransient
on the parent and @XmlElement
on the child:
Parent
package forum7851052;import java.util.ArrayList;import java.util.List;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlTransient;@XmlRootElementpublic class Parent<T> { private List<T> item = new ArrayList<T>(); @XmlTransient public List<T> getItem() { return item; } public void setItem(List<T> item) { this.item = item; }}
IntegerChild
package forum7851052;import java.util.List;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class IntegerChild extends Parent<Integer> { @Override @XmlElement public List<Integer> getItem() { return super.getItem(); } @Override public void setItem(List<Integer> item) { super.setItem(item); }}
StringChild
package forum7851052;import java.util.List;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class StringChild extends Parent<String> { @Override @XmlElement public List<String> getItem() { return super.getItem(); } @Override public void setItem(List<String> item) { super.setItem(item); }}
Demo
package forum7851052;import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Parent.class, IntegerChild.class, StringChild.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); IntegerChild integerChild = new IntegerChild(); integerChild.getItem().add(1); integerChild.getItem().add(2); marshaller.marshal(integerChild, System.out); StringChild stringChild = new StringChild(); stringChild.getItem().add("A"); stringChild.getItem().add("B"); marshaller.marshal(stringChild, System.out); }}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><integerChild> <item>1</item> <item>2</item></integerChild><?xml version="1.0" encoding="UTF-8" standalone="yes"?><stringChild> <item>A</item> <item>B</item></stringChild>