Quantcast
Channel: Jackson XML Serialization: Nested Element with Same Name as Parent - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Jackson XML Serialization: Nested Element with Same Name as Parent

$
0
0

I have a complex xml type with a nested element whose name is the same as the parent, but when I serialize it the nested element gets set as the text of the parent when it is included in another element.

The DTOs looks like this:

@JacksonXmlRootElement(localName = "address")public class Address{    @JacksonXmlText(false)    @JsonProperty    private String address;    @JsonProperty    private String city;    //getters and setters}@JacksonXmlRootElement(localName = "person")public Person {    private String name;    private Address address;}

My XmlMapper configuration:

XmlMapper xmlMapper = XmlMapper.xmlBuilder()    .defaultUseWrapper(false)    .serializationInclusion(NON_NULL)    .build();xmlMapper.getFactory()    .getXMLOutputFactory()    .setProperty("javax.xml.stream.isRepairingNamespaces", false);

When I serialize an Address on it's own, I get the expected value:

<address><address>123 East Street</address><city>metropolis</city></address>

But when I serialize an Address as a nested object of another DTO, like Person, then the address property is serialized as text of the Address parent object.

Actual XML:

<person><address>123 East Street<city>metropolis</city></address></person>

Expected XML:

<person><address><address>123 East Street</address><city>metropolis</city></address></person>

I already know that this is just bad XML design, but that is what I have to do!

Any ideas on how to get the expected XML output?

Edits

I found a workaround by creating another DTO with a "value" field marked as text.

@JacksonXmlRootElement(localName = "address")public class StreetAddress{    @JacksonXmlText    private String value;    //getters and setters}//snip@JacksonXmlRootElement(localName = "address")public class Address{    @JsonProperty    private StreetAddress address;    @JsonProperty    private String city;    //getters and setters}

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>