1

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
}
Community
  • 1
  • 1
Pytry
  • 6,044
  • 2
  • 37
  • 56

1 Answers1

1

When wiring the DTOs like follows, the XML output is produced like expected. I used version 2.10 of jackson-annotations and jackson-dataformat-xml. No differences to the code except additional getters and setters.

Address a = new Address();
a.setCity("metropolis");
a.setAddress("123 East Street");
Person p = new Person();
p.setAddress(a);
xmlMapper.writeValue(new PrintWriter(System.out), p);

Output

<person><address><address>123 East Street</address><city>metropolis</city></address></person>
ldz
  • 2,217
  • 16
  • 21
  • I'll have to setup a better example project, since I am definitely still getting that error. I did find a work around, which I will add as an edit. – Pytry Dec 11 '19 at 16:45
  • I think it might be that I am using the oracle stax implementation instead of woodstox (also a requirement). – Pytry Dec 11 '19 at 16:52