Search code examples
javaspring-bootkotlinjacksonjackson-dataformat-xml

Why is @JacksonXmlProperty ignoring parameters in Spring Boot with Kotlin?


So I'm trying to serialize/deserialize RSS feeds using Jackson XML in Kotlin. However, currently it's not doing either properly. When I instantiate the RSS object manually and print out the xml, it seems like it's ignoring the localName and namespace parameters in @JacksonXmlProperty. Here is my code:

@JacksonXmlRootElement(localName="rss")
class RSSFeed(
    @JacksonXmlProperty(localName="channel")
    var channel: Channel
) {
    constructor() : this(Channel())
}

class Channel(
    @JacksonXmlProperty(localName="title")
    var title: String? = null,

    @JacksonXmlCData
    @JacksonXmlProperty(localName="description")
    var description: String? = null,


    @JacksonXmlProperty(localName="image")
    var image: RSSImage? = null,

    @JacksonXmlProperty(localName = "explicit", namespace="itunes")
    var isExplicit: String? = "no",

    @JacksonXmlProperty(localName = "pubDate")
    var publishDate: String? = null,

    @JacksonXmlProperty(localName = "type", namespace="itunes")
    var episodeType: String? = null,

    @JacksonXmlProperty(localName = "link", namespace="atom")
    var atomLink: AtomLink? = null,

    @JacksonXmlProperty(localName = "new-feed-url", namespace="itunes")
    var newFeedUrl: String? = null
)

Then I just do:

println(XmlMapper().writeValueAsString(RSSFeed(Channel(title = "blah", description = "blah", image = RSSImage(url = "https://someurl.com", link = "somelink"), isExplicit = "yes", atomLink = AtomLink(href="blah.com"), newFeedUrl = "thisisthenewfeed"))))

However, when I print that out it ignores the namespace and localName properties and just uses the variable names. What am I doing wrong?

Xml output: <rss><channel><title>blah</title><description><![CDATA[blah]]></description><image><url>https://someurl.com</url><title/><link><![CDATA[somelink]]></link></image><publishDate/><episodeType/><atomLink href="blah.com"/><newFeedUrl>thisisthenewfeed</newFeedUrl></channel></rss>

edit: it also doesn't seem to be printing the isExplicit property for some reason, not sure what that's about.


Solution

  • Well I figured it out! It turns out this was a Kotlin issue. I just had to do this: val xmlMapper = XmlMapper().registerModule(KotlinModule())

    ...and make sure that this is in your dependencies (I use gradle):

    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

    Anyways I hope this helps someone in the future.