Search code examples
xmlkotlinjacksonjackson-dataformat-xml

Deserializing xml namespaces with Jackson & Kotlin


I have a xml element with 2 namespaces, and I'm not able to read them with jackson.

<Person xmlns="http://some.namespace.com" xmlns:ns0="http://some.other.namespace.com">
    <name>John</name>
</Person>
internal data class Person(
    val name: String,
    @get:JacksonXmlProperty(isAttribute = true)
    val xmlns: String,
    @get:JacksonXmlProperty(isAttribute = true, localName="xmlns:ns0")
    val ns0: String
)

When reading the XML with jackson, I get an error saying that both namespaces should be nullable.

I've tried with some variants like attrs in the body of the class and with the namespace attribute, like

    @JacksonXmlProperty(isAttribute = true, localName = "ns0", namespace = "xmlns")
    var ns0: String? = null

This is the mapper I'm using

val mapper: XmlMapper = XmlMapper().apply {
        registerModule(KotlinModule())
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
    }

How can I read and write again this xml and make them identical?


Solution

  • I solved my problem setting a property to the XMLInputFactory like this:

    val inputFactory = XMLInputFactory.newFactory()
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false)
    XmlMapper(inputFactory).apply {
       registerModule(KotlinModule())
    }
    

    In this case you can model all the namespaces and do what you want. Case solved.