在kotlin中使用时,@XmlElement不起作用
当我序列化一个类ReturnValue
的实例时,我发现@XmlElement
不起作用。 生成的XML仍然有<summary>
的标签,而不是<comment>
。
ReturnValue类:
@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") }
测试程序:
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) }
和输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><returnValue><type>type2</type><summary>hello</summary></returnValue>
所以,我想把<summary>
改成<comment>
。 我怎样才能做到这一点?
JAXB是一个Java API,它期望事情看起来像Java通常做的事情,而Kotlin做的事情略有不同。
为了对JAXB的参数进行注释,必须使用@field:XmlElement
以便将注释放在Kotlin参数所转换的Java字段上,如下所示:
@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") }
更多信息:在Kotlin文档中注释使用站点目标 。