所以我尝试在 Kotlin 中使用 Jackson XML 序列化/反序列化 RSS 提要。然而,目前它两者都做得不好。当我手动实例化 RSS 对象并打印出 xml 时,它似乎忽略了 localName
和namespace
@JacksonXmlProperty 中的参数。这是我的代码:
@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
)
然后我就这样做:
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"))))
但是,当我打印出来时,它会忽略 namespace 和 localName 属性,而只使用变量名称。我做错了什么?
XML 输出:<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>
编辑:由于某种原因,它似乎也没有打印 isExplicit 属性,不确定那是什么。
最佳答案
好吧,我明白了!事实证明这是一个 Kotlin 问题。我只需要这样做: val xmlMapper = XmlMapper().registerModule(KotlinModule())
...并确保它在您的依赖项中(我使用 gradle):
实现(“com.fasterxml.jackson.module:jackson-module-kotlin”)
无论如何,我希望这对将来的人有所帮助。
关于java - 为什么 @JacksonXmlProperty 在使用 Kotlin 的 Spring Boot 中忽略参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60895872/