我想制作一个自定义 List 序列化程序,可以安全地解析无效的 json 数组。示例: Int 列表[1, "invalid_int", 2]
应解析为[1, 2]
. 我已经制作了一个序列化程序并将其添加到 Json 提供程序,但是在第一个元素之后序列化一直失败并且无法继续,所以我得到了 1 个元素的列表[1]
,如何正确处理无效元素以便解码器继续解析其他元素?
class SafeListSerializerStack<E>(val elementSerializer: KSerializer<E>) : KSerializer<List<E>> {
override val descriptor: SerialDescriptor = ListSerializer(elementSerializer).descriptor
override fun serialize(encoder: Encoder, value: List<E>) {
val size = value.size
val composite = encoder.beginCollection(descriptor, size)
val iterator = value.iterator()
for (index in 0 until size) {
composite.encodeSerializableElement(descriptor, index, elementSerializer, iterator.next())
}
composite.endStructure(descriptor)
}
override fun deserialize(decoder: Decoder): List<E> {
val arrayList = arrayListOf<E>()
try {
val startIndex = arrayList.size
val messageBuilder = StringBuilder()
val compositeDecoder = decoder.beginStructure(descriptor)
while (true) {
val index = compositeDecoder.decodeElementIndex(descriptor) // fails here on number 2
if (index == CompositeDecoder.DECODE_DONE) {
break
}
try {
arrayList.add(index, compositeDecoder.decodeSerializableElement(descriptor, startIndex + index, elementSerializer))
} catch (exception: Exception) {
exception.printStackTrace() // falls here when "invalid_int" is parsed, it's ok
}
}
compositeDecoder.endStructure(descriptor)
if (messageBuilder.isNotBlank()) {
println(messageBuilder.toString())
}
} catch (exception: Exception) {
exception.printStackTrace() // falls here on number 2
}
return arrayList
}
}
解析无效元素并引发异常后发生错误compositeDecoder.decodeElementIndex(descriptor)
:
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 4: Expected end of the array or comma
JSON input: [1, "invalid_int", 2]
我有一种感觉,它应该“吞下”无效元素并继续移动,但它却卡住了,无法继续解析,这对我来说没有意义。