Search code examples
javaxmljacksonjackson-dataformat-xml

Serialization with Jackson XmlMapper


I'm trying to serialize object to xml string with Jackson XmlMapper. My object is:

@JacksonXmlRootElement(namespace = "http://www.w3.org/2001/XMLSchema", localName = "PersonRO")
public class PersonInfo {

    @JacksonXmlProperty(localName = "PersonID")
    private String personId;

    @JacksonXmlProperty(localName = "ReturnCode")
    private Integer errorCode;

    // getters, setters
}

I need to achieve following xml in output:

        <PersonRO xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <PersonID>00000000000001</PersonID>
          <ReturnCode>150</ReturnCode>
        </PersonRO>

The task seems easy, but first of all I have a problem with achieving multiple namespases (xmlns:xsd, xmlns:xsi), and also have empty namespaces for fields, although I don't need them at all.

So far my result is:

<PersonRO xmlns="http://www.w3.org/2001/XMLSchema">
  <PersonID xmlns="">00000000000001</PersonID>
  <ReturnCode xmlns="">150</ReturnCode>
</PersonRO>

So, how can I achieve exactly the same result as above, using Jackson XmlMapper? (I've seen that you can configure XmlFactory, etc., but can not do it properly...)

If you need any clarification, please let me know and thank you in advance.


Solution

  • I have found the answer:

    @JacksonXmlRootElement(localName = "PersonRO")
    public class PersonInfo {
    
        @JacksonXmlProperty(isAttribute = true, localName = "xmlns:xsd")
        private final String xmlnsXsd = "http://www.w3.org/2001/XMLSchema";
    
        @JacksonXmlProperty(isAttribute = true, localName = "xmlns:xsi")
        private final String xmlnsXsi = "http://www.w3.org/2001/XMLSchema-instance";
    
    
        @JacksonXmlProperty(localName = "PersonID")
        private String personId;
    
        @JacksonXmlProperty(localName = "ReturnCode")
        private Integer errorCode;
    
        // getters, setters
    }