So I try to deserialize XML to Kotlin data classes...
# jackson-kotlin
s
So I try to deserialize XML to Kotlin data classes. The only problem is when a node has attributes and content/text like this logo:
Copy code
val logo = kotlinXmlMapper.readValue<ImageUrl>(
"""<logo height="50" width="150">https://images.somepage.com/images/logos/150x50/currysnewlogo.gif</logo>"""
)
Here is my data class:
Copy code
data class ImageUrl(
        val height: Int,
        val width: Int,
        @JacksonXmlText val url: String
)
@JacksonXmlText should be the answer but it’s not:
Copy code
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid definition for property `` (of type `com.example.demoxmlprocessing.ImageUrl`): Could not find creator property with name '' (known Creator properties: [height, width, url])
my jackson dependencies: (version 2.9.9 is used)
Copy code
implementation("org.springframework.boot:spring-boot-starter-web-services")
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
the mapper definition:
Copy code
internal val kotlinXmlMapper = XmlMapper(JacksonXmlModule().apply {
    setDefaultUseWrapper(false)
}).registerModule(KotlinModule())
        .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
UPDATE: FIXED IT I had to specify the name to use for the body text
Copy code
internal val kotlinXmlMapper = XmlMapper(JacksonXmlModule().apply {
    setDefaultUseWrapper(false)
    setXMLTextElementName("body")
}).registerModule(KotlinModule())
        .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
Now I can map that name to my property:
Copy code
data class ImageUrl(
        val height: Int,
        val width: Int,
        @JacksonXmlText @JsonProperty("body") val url: String
)
288 Views