SicaYoumi
SicaYoumi

Reputation: 186

XML unmarshal to Object in Java/Kotlin

I want to change a xml string to a object but it seems like keeps throwing error to me and I'm not sure how to use those @XmlRootElement stuff

Just view/reply it as JAVA also can although written in kotlin

Here it's the XML string

<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>

Here it's my data class

@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
)

Here it's my code, "xmlreturn" is the xml string

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

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

Here it's the error

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)

I know probably i need to add something into the data class but i don know what to add. Thanks in advance.

Upvotes: 0

Views: 2947

Answers (1)

Roland
Roland

Reputation: 23262

Your root element's name differs from your xml root element, which also the message suggests. It expects wxPayResult, but you give it a xml.

Either deliver an XML with wxPayResult as root element or supply the name to XMLRootElement, e.g.

@XmlRootElement(name = "xml")

Upvotes: 2

Related Questions