gpt4 book ai didi

java - Java/Kotlin 中 XML 解码为对象

转载 作者:行者123 更新时间:2023-12-02 01:58:34 25 4
gpt4 key购买 nike

我想将 xml 字符串更改为对象,但似乎一直向我抛出错误,并且我不确定如何使用那些 @XmlRootElement 内容

只需查看/回复即可,JAVA 也可以,尽管是用 kotlin 编写的

这是 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)

我知道我可能需要在数据类中添加一些东西,但我不知道要添加什么。提前致谢。

最佳答案

您的根元素的名称与 xml 根元素的名称不同,消息也表明了这一点。它需要 wxPayResult,但您给它一个 xml

要么提供一个以 wxPayResult 作为根元素的 XML,要么向 XMLRootElement 提供 name,例如

@XmlRootElement(name = "xml")

关于java - Java/Kotlin 中 XML 解码为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51982093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com