在正常的序列化发生之前,您可以使用Json transformation来更改您收到的JSON.
本课程:
class EntryPreSerializer : JsonTransformingSerializer<Entry>(Entry.serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement {
return if (element is JsonPrimitive)
buildJsonObject {
put("type", JsonPrimitive("StringEntry"))
put("text", element)
}
else element
}
}
当应用于序列化的Entry
对象(我们的多态类)时,它将添加我们在entries
中发现JSON原语时进行多态反序列化所需的鉴别器.
为了完成该示例,以下是填充的反序列化的其余部分,包括显示我们如何应用转换:
@Serializable
data class EntryWrapper(val entries: List<@Serializable(with = EntryPreSerializer::class) Entry>)
@Serializable
sealed class Entry
@Serializable
data class StringEntry(val text: String) : Entry()
@Serializable @SerialName("list")
data class ListEntry(val items: List<String>) : Entry()
@Serializable @SerialName("entries")
data class EntriesEntry(val name: String, val entries: List<String>) : Entry()
然后我们可以测试:
fun main() {
val testJson = """
{
"entries": [
"Simple Text",
{
"type": "list",
"items": [
"First Item",
"Second Item",
"Spectral wings appear on your back, giving you a flying speed of 40 feet."
]
},
{
"type": "entries",
"name": "Sub-Entry",
"entries": [
"New text but could also be the same as above"
]
}
]
}
""".trimIndent()
println(Json.decodeFromString<EntryWrapper>(testJson))
}
它打印:
EntryWrapper(entries=[StringEntry(text=Simple Text), ListEntry(items=[First Item, Second Item, Spectral wings appear on your back, giving you a flying speed of 40 feet.]), EntriesEntry(name=Sub-Entry, entries=[New text but could also be the same as above])])