我正在尝试使用依赖项为Color
类制作自定义序列化程序。kmongo-coroutine-serialization
这样做时我遇到了一个例外:
Exception in thread "main" org.bson.BsonInvalidOperationException: readEndDocument can only be called when State is END_OF_DOCUMENT, not when State is VALUE.
我将其作为 json 测试的文档
{
"_id": {
"$oid": "61fe4f745064370bd1473c41"
},
"id": 1,
"color": "#9ac0db"
}
ExampleDocument
班级:
@Serializable
data class ExampleDocument(
@Serializable(with = ColorHexSerializer::class) val color: Color
)
ColorHexSerializer
对象:
出于测试目的,我总是返回蓝色
internal object ColorHexSerializer : KSerializer<Color> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("color_hex", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Color) {
val hex = String.format("#%06x", value.rgb and 0xFFFFFF)
encoder.encodeString(hex)
}
override fun deserialize(decoder: Decoder): Color {
return Color.BLUE
}
}
主功能:
suspend fun main() {
registerSerializer(ColorHexSerializer)
val document =
KMongo.createClient("connectionString")
.getDatabase("database")
.getCollectionOfName<ExampleDocument>("testing")
.find(eq("id", 1))
.awaitFirst()
}
将 bson 文档转换为 json 并对其进行反序列化,然后使用 kotlinxserialization 就可以了。有人能帮我一下吗?
提前致谢