我正在尝试使用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工作得很好。这里有人能帮我吗?
提前感谢
发布于 2022-02-09 15:54:13
反序列化过程采用解码器,并向他请求由反序列化器串行形式定义的原语元素序列,而解码器知道如何从实际格式表示中检索这些原语元素。
和
更具体地说,序列化要求解码器提供一个序列“给我一个int,给我一个双,给我一个字符串列表,并给我一个嵌套的int对象”。
您需要按顺序指定从解码器读取的所有值。所有写入的值也需要读取。kotlinx.serialization似乎忽略了在kmongo抛出异常时读取剩余内容的错误(至少在您的情况下是这样)。
默认情况下,通过返回蓝色颜色,可以跳过读取字符串的步骤,导致字符串将被留下。
由于还剩一个字符串,所以对象的状态是VALUE (在尝试完成文档读取时,还有一个要读取的值)。
override fun deserialize(decoder: Decoder): Color {
decoder.decodeString()
return Color.BLUE
}https://stackoverflow.com/questions/71040195
复制相似问题