【发布时间】:2021-04-21 12:25:51
【问题描述】:
我的数据是富文本格式,存储为嵌套的 JSON 数组。文本标记存储字符串的纯文本和描述格式的注释。我想在解码时将这些嵌套 JSON 数组的特定结构映射到丰富的 Kotlin 类层次结构。
这是描述此文本编码的打字稿类型:
// Text string is an array of tokens
type Text = Array<TextToken>
// Each token is a Array[2] tuple. The first element is the plaintext.
// The second element is an array of annotations that format the text.
type TextToken = [string, Array<Annotation>]
// My question is about how to serialize/deserialize the Annotation type
// to a sealed class hierarchy.
//
// Annotations are an array where the first element is always a type discriminator string
// Each annotation type may have more elements, depending on the annotation type.
type Annotation =
| ["b"] // Text with this annotation is bold
| ["i"] // Text with this annotation is italic
| ["@", number] // User mention
| ["r", { timestamp: string, reminder: string }] // Reminder
我已经定义了一些 Kotlin 类来使用 sealed class 来表示相同的东西。这是反序列化 JSON 后我想要的输出格式:
// As JSON example: [["hello ", []], ["Jake", [["b"], ["@", 1245]]]]
data class TextValue(val tokens: List<TextToken>)
// As JSON example: ["hello ", []]
// As JSON example: ["Jake", [["b"], ["@", 1245]]]
data class TextToken(val plaintext: String, val annotations: List<Annotation>)
sealed class Annotation {
// As JSON example: ["b"]
@SerialName("b")
object Bold : Annotation()
// As JSON example: ["i"]
@SerialName("i")
object Italic : Annotation()
// As JSON example: ["@", 452534]
@SerialName("@")
data class Mention(val userId: Int)
// As JSON example: ["r", { "timestamp": "12:45pm", "reminder": "Walk dog" }]
@SerialName("r")
data class Reminder(val value: ReminderValue)
}
如何定义我的序列化程序?我尝试使用JsonTransformingSerializer 定义序列化程序,但是当我尝试为我的一个类包装默认序列化程序时出现空指针异常:
@Serializable(with = TextValueSerializer::class)
data class TextValue(val tokens: List<TextToken>)
object TextValueSerializer : JsonTransformingSerializer<TextValue>(TextValue.serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement {
return JsonObject(mapOf("tokens" to element))
}
override fun transformSerialize(element: JsonElement): JsonElement {
return (element as JsonObject)["tokens"]!!
}
}
Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.json.JsonTransformingSerializer.<init>, parameter tSerializer
at kotlinx.serialization.json.JsonTransformingSerializer.<init>(JsonTransformingSerializer.kt)
at example.TextValueSerializer.<init>(TextValue.kt:17)
【问题讨论】:
标签: json typescript kotlin kotlinx.serialization