blog podcast

XML and Jackson

XML to me represent bad developer practice. It is heavy weight and strict. Unsupportive of deviation and hence brittle. It’s something that might sound good in theory in some University but becomes your pain in practice in the real world. Still, sometimes you have to engage with this Neanderthal sibling to Json. In the JVM world you have Jackson to support you with this. In gradle something like this:

    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.1'

When you start coding with this you might encounter a problem. Unlike Json where you have objects, arrays and primitives, XML can also have attributes on its elements. This means that what your programming language finally maps to properties might either come from child elements of an XML element, or from attributes on this element. For example the following element:

                            <MediaFile id="5241" delivery="progressive" type="video/mp4" bitrate="2000" width="1280" height="720" minBitrate="1500" maxBitrate="2500" scalable="1" maintainAspectRatio="1" codec="H.264">

The question becomes, how do you map Whatever to a property on your class? In Kotlin the solution would look something like this:

data class MediaFileDto(
    @field:JacksonXmlProperty(isAttribute = true, localName = "id")
    var id: String = "",
    @field:JacksonXmlProperty(isAttribute = true, localName = "type")
    var type: String = "",
    @field:JacksonXmlProperty(isAttribute = true, localName = "delivery")
    var delivery: String = "",
    @field:JacksonXmlProperty(isAttribute = true, localName = "bitrate")
    var bitrate: String = "",
    @field:JacksonXmlProperty(isAttribute = true, localName = "codec")
    var codec: String = "",
    var value: String = ""

Here the value property gets the value from inside the node.