无法使用JAXB和Kotlin解组xml对象的集合

时间:2017-07-29 19:10:38

标签: xml jaxb jvm kotlin

我正在尝试反序列化/解组包含People标记中包含的Person元素集合的XML。我试图使用JAXB在Kotlin中反序列化这个XML。一切都编译并运行没有错误,但我班上的人员集合总是空的。我如何解组这个系列?

import java.io.StringReader
import javax.xml.bind.JAXB
import javax.xml.bind.annotation.XmlAccessType
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlElementWrapper

@XmlAccessorType(XmlAccessType.FIELD)
data class Person(
        var name:String = "",
        var age:Int = 0
)

@XmlAccessorType(XmlAccessType.FIELD)
data class Report(
        var statusCode:Int = 0,
        @XmlElementWrapper(name = "people")
        @XmlElement(name = "person")
        var people:List<Person>? = null
)

val xml = """
<report>
    <statusCode>3</statusCode>
    <people>
        <person>
            <name>Bob</name>
            <age>30</age>
        </person>
        <person>
            <name>Alice</name>
            <age>40</age>
        </person>
    </people>
</report>
"""

fun main(args: Array<String>) {
    val report = JAXB.unmarshal(StringReader(xml), Report::class.java)
    println(report) // Report(statusCode=3, people=[])
}

1 个答案:

答案 0 :(得分:5)

这是因为您将XmlAccessType定义为FIELD,因此您应该使用site target在支持field上注释注释,例如:

// v--- annotated on field rather than getter/setter/params
@field:[XmlElementWrapper(name = "people") XmlElement(name = "person")]
var people: List<Person>? = null