Skip to content

Instantly share code, notes, and snippets.

@mKeRix
Created March 4, 2021 19:22
Show Gist options
  • Save mKeRix/526aae97ae51a2be4fec750522449c02 to your computer and use it in GitHub Desktop.
Save mKeRix/526aae97ae51a2be4fec750522449c02 to your computer and use it in GitHub Desktop.
Jackson XML Polymorph List
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
@JacksonXmlRootElement
class Parent {
@JacksonXmlProperty(localName = "Book")
@JacksonXmlElementWrapper(useWrapping = false)
var books: List<Book> = ArrayList()
set(value) {
field = books + value
}
}
data class Book(
@JacksonXmlProperty
val title: String
)
val kotlinModule: KotlinModule = KotlinModule.Builder()
.strictNullChecks(false)
.nullIsSameAsDefault(true) // needed, else it will break for null https://github.com/FasterXML/jackson-module-kotlin/issues/130#issuecomment-546625625
.build()
val xmlMapper =
XmlMapper(JacksonXmlModule())
.registerModule(kotlinModule)
.registerModule(JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // to parse the dates as LocalDate, else parsing error
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
val input = """
<Parent>
<Book title="Book 1" />
<Something />
<Book title="Book 2" />
<Something />
<Book title="Book 3" />
</Parent>
""".trimIndent()
val mappedValues = xmlMapper.readValue<Parent>(input)
println(mappedValues.books)
// outputs [Book(title=Book 1), Book(title=Book 2), Book(title=Book 3)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment