When I serialize an instance of class ReturnValue
, I found that @XmlElement
doesn't work. the generated xml still had a tag of <summary>
, not <comment>
.
the ReturnValue class:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
@XmlElement(name="comment")
val summary: String){
constructor(): this(type="java.lang.Object", summary="no summary")
}
the test program:
fun main(args: Array<String>) {
val jaxbContext = JAXBContext.newInstance(ReturnValue::class.java)
val marshaller = jaxbContext.createMarshaller()
marshaller.marshal(
ReturnValue(type = "java.lang.Object",summary = "hello"),
System.out)
}
and the output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><returnValue><type>type2</type><summary>hello</summary></returnValue>
So, I want to change <summary>
to <comment>
. How can I do that?
JAXB is a Java API, which expects things to look the way that Java normally does things, and Kotlin does things slightly differently.
To annotate the parameter so that it looks correct to JAXB, you have to use @field:XmlElement
so that the annotation is put on the Java field that the Kotlin parameter translates to, like this:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
@field:XmlElement(name = "comment") val summary: String) {
constructor() : this(type = "java.lang.Object", summary = "no summary")
}
More information: Annotation Use-site Targets in the Kotlin documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With