Kotlin - 使用 Jackson XmlMapper 反序列化
我在使用 Jackson XML Mapper 正确解析 XML 文件时遇到一些问题。 假设我有这个简单的 XML:
<Test>
<Simple>
<x>I am x</x>
<y>I am y</y>
</Simple>
</Test>
和这个简单的类:
@Root(name="Simple",strict = false)
class Simple {
@Element(name = "x", required = false)
lateinit var x :String
@Element(name = "y", required = false)
lateinit var y :String
}
编译器不断抛出此错误:
线程“main”中的异常 com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段“Simple”(类 Simple),未标记为可忽略(2 个已知属性:“x”、“y”])
我猜这是因为 Kotlin 找不到文件的正确结构班级内? 问题是我需要解析一个更大的 xml 文件,并且需要避免镜像 xml 的每个元素,否则它将变得巨大。
那么如何“部分”解析 xml,将根设置为
标记,避免使用
标记呢?
太感谢了!
I'm having some trouble to parse correctly an XML file with Jackson XML Mapper.
Suppose I have this simple XML:
<Test>
<Simple>
<x>I am x</x>
<y>I am y</y>
</Simple>
</Test>
and this simple class:
@Root(name="Simple",strict = false)
class Simple {
@Element(name = "x", required = false)
lateinit var x :String
@Element(name = "y", required = false)
lateinit var y :String
}
The compiler keeps throwing this error:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Simple" (class Simple), not marked as ignorable (2 known properties: "x", "y"])
I guess it's because Kotlin can't find the proper structure of the file within the class?
Problem is I need to parse a much more big xml file, and need to avoid to mirror every single Element of the xml, otherwise it will become huge.
So how can I "partially" parse the xml, setting the root to the <Simple>
tag, avoiding the <Test>
tag?
Thank you so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个可行的解决方案。请注意,我已使映射器不区分大小写,以应对 XML 中大写的 Simple 属性。您可以使用属性上的注释来执行此操作,而不是覆盖默认的小写名称。另请注意,数据类的使用消除了使用 Lateinit vars 等的任何需要:
确保您的 build.gradle.kts 具有这些依赖项(如果它们尚不存在):
Here's a working solution. Note that I've made the mapper case insensitive to cope with the capitalised Simple property in the XML. You could do this with an annotation on the property instead to override the default lower case name. Note also the use of data classes that do away with any need to use lateinit vars or suchlike:
make sure your build.gradle.kts has these dependencies if they aren't there already: