XML解组到Java / Kotlin中的对象

时间:2018-08-23 09:06:49

标签: java xml kotlin jaxb unmarshalling

我想将xml字符串更改为一个对象,但似乎不断向我抛出错误,我不确定如何使用这些@XmlRootElement东西

尽管用kotlin编写,也可以像JAVA一样查看/回复它

这是XML字符串

<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<appid><![CDATA[wx0b6dc231d20b379f1]]></appid>
<mch_id><![CDATA[1508319851]]></mch_id>
<nonce_str><![CDATA[mqy4nB6xGoyC1QPY]]></nonce_str>
<sign><![CDATA[2D9A3195E196F679D3916C5DC74754B4]]></sign>
<result_code><![CDATA[SUCCESS]]></result_code>
<prepay_id><![CDATA[wx2116190646297891sfae86747980208850875]]></prepay_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
</xml>

这是我的数据类

@XmlRootElement
data class  WxPayResult(


val return_code: String = "",

val return_msg: String = "",


//return_code as SUCCESS will only return the following params
val appid: String? = null,

val mch_id: String? = null,

val device_info: String? = null,

val nonce_str: String? = null,

val sign: String? = null,

val result_code: String? = null,

val err_code: String? = null,

val err_code_des: String? = null,


//return_code and result_code both as success will only return the following params
val trade_type: String? = null,

val prepay_id: Int? = null,

val code_url: String? = null
)

这是我的代码,“ xmlreturn”是xml字符串

val jaxbContext = JAXBContext.newInstance(WxPayResult::class.java)
        val unmarshaller = jaxbContext.createUnmarshaller()

        val reader = StringReader(xmlreturn)
        val person = unmarshaller.unmarshal(reader)

这是错误

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"xml"). Expected elements are <{}wxPayResult>
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:741)
    at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:262)
    at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:257)
    at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:124)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1149)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:574)

我知道我可能需要在数据类中添加一些内容,但是我不知道要添加什么内容。预先感谢。

1 个答案:

答案 0 :(得分:2)

您的根元素的名称与xml根元素的名称不同,这也提示该消息。它期望wxPayResult,但是您给它一个xml

例如,以wxPayResult为根元素交付XML,或者将name提供给XMLRootElement,例如

@XmlRootElement(name = "xml")