我有以下XML结构(基于Qt文件格式)来反序列化:
<context>
<name>General</name>
<message>
<source>One</source>
<translation>One</translation>
</message>
<message>
<source>Two</source>
<translation>Two</translation>
</message>
<message numerus="yes">
<source>Thing</source>
<translation>
<numerusform>Thing</numerusform>
<numerusform>Things</numerusform>
</translation>
</message>
</context>解析这一点的Kotlin代码:
data class Context(@JacksonXmlProperty(localName = "name")
val name: String = "",
private val mMap: MutableList<Message> = mutableListOf()) {
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "message")
var messages = mMap
set(value) {
field.addAll(value); return
}
}
data class Message(@JacksonXmlProperty(localName = "numerus", isAttribute = true)
val numerus: String? = null,
@JacksonXmlProperty(localName = "source")
val source: String? = null,
@JacksonXmlProperty(localName = "comment")
val comment: String? = null,
@JacksonXmlProperty(localName = "translation")
val translation: Translation? = null)
data class Translation(@JacksonXmlProperty(localName = "type", isAttribute = true)
val type: String? = null,
@JacksonXmlProperty(localName = "innerText")
@JacksonXmlText
val text: String? = null,
private val numerusMap: MutableList<NumerusForm> = mutableListOf()) {
// custom setter because otherwise the list isn't assembled correctly
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "numerusform")
var numerusForm = numerusMap
set(value) {
field.addAll(value); return
}
}
data class NumerusForm(@JacksonXmlProperty(localName = "innerText")
@JacksonXmlText
val text: String? = null
)如果只有
<translation
<numerusform>Thing</numerusform>
</translation> XML中可用的属性。只要我有了<translation>One</translation>,它就会崩溃。
是否知道如何解析这个仅偶尔出现在XML结构中的属性,而不会影响文件的其余部分?
发布于 2021-08-10 11:04:57
通过从Jackson创建我自己的反序列化器类来找到解决方案。
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
class MyOwnDeserizalizer : StdDeserializer<TSTransformerService.Translation>(Translation::class.java) {
override fun deserialize(jP: JsonParser, ctxt: DeserializationContext): Translation {
//Gets the Translation element
val rootNode: JsonNode = jP.getCodec().readTree<JsonNode>(jP)
// Get and set the value from the rootnode
return Translation(type, text, numerus)
}
}一些资料来源帮助:
https://stackoverflow.com/questions/68639386
复制相似问题