Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@XmlElement does not work when used in kotlin

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?

like image 278
owl Avatar asked Nov 01 '17 07:11

owl


1 Answers

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.

like image 101
Jesper Avatar answered Nov 04 '22 16:11

Jesper