Search code examples
javaxmljacksonmarshalling

Jackson XML ArrayList output having two wrapper elements


I am getting two wrapper elements in the XML output generated by Jackson. I would like to have only one.

I have a Java bean

@Entity
@Table(name = "CITIES")
@JacksonXmlRootElement(localName = "City")
public class City implements Serializable {

    private static final long serialVersionUID = 21L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JacksonXmlProperty(isAttribute = true)
    private Long id;

    @JacksonXmlProperty    
    private String name;

    @JacksonXmlProperty
    private int population;

    // getters, setters etc
}

and a List wrapper class.

@JacksonXmlRootElement
public class Cities implements Serializable {

    private static final long serialVersionUID = 22L;

    @JacksonXmlProperty(localName = "City")
    @JacksonXmlElementWrapper(localName = "MyCities")
    private List<City> cities = new ArrayList<>();

    public List<City> getCities() {
        return cities;
    }

    public void setCities(List<City> cities) {
        this.cities = cities;
    }
}

I am getting this output, which has two wrapper elements. I would like to remove one of them.

<Cities>
  <MyCities>
    <City id="1">
      <name>Bratislava</name>
      <population>432000</population>
    </City>
    <City id="2">
      <name>Budapest</name>
      <population>1759000</population>
    </City>
    <City id="3">
      <name>Prague</name>
      <population>1280000</population>
    </City>
  <MyCities>
</Cities>

One of them comes from the ArrayList, one from the class. How to get rid of one of the wrapper elements?

What I want to have is this:

<Cities>
    <City id="1">
      <name>Bratislava</name>
      <population>432000</population>
    </City>
    <City id="2">
      <name>Budapest</name>
      <population>1759000</population>
    </City>
    <City id="3">
      <name>Prague</name>
      <population>1280000</population>
    </City>
</Cities>

Solution

  • "Cities" is the root element, not a wrapper. Wouldn't removing the actual wrapper element "MyCities" work?

    Adding @JacksonXmlElementWrapper(useWrapping = false) could also help.