-
Notifications
You must be signed in to change notification settings - Fork 652
Open
Description
Describe the bug
In a custom deserialization for a JSON array I want to use JsonDecoder.decodeJsonElement()
. I call decodeElementIndex
, and expect it to return the next item in the JSON array. This works when decoding from a string (Json.decodeFromString
), but doesn't work when decoding from a JsonElement (Json.decodeFromJsonElement
)
To Reproduce
fun main() {
val str = """[1,2]"""
val json: JsonArray = Json.parseToJsonElement(str) as JsonArray
val fromString: List<JsonElement> = Json.decodeFromString(JsonElementListSerializer, str)
val fromJsonElement: List<JsonElement> = Json.decodeFromJsonElement(JsonElementListSerializer, json)
println("$fromJsonElement should equal $fromString")
// OUTPUT: [[1,2], [1,2]] should equal [1, 2]
}
object JsonElementListSerializer : DeserializationStrategy<List<JsonElement>> {
override val descriptor: SerialDescriptor = ListSerializer(JsonElement.serializer()).descriptor
override fun deserialize(decoder: Decoder): List<JsonElement> = buildList {
decoder.decodeStructure(descriptor) {
while (true) {
val index = decodeElementIndex(descriptor)
if (index == CompositeDecoder.DECODE_DONE) break
add((this as JsonDecoder).decodeJsonElement())
}
}
}
}
Expected behavior
The resulting list with both methods should be the same, and contain only JsonPrimitives, never JsonArrays.
Environment
- Kotlin version: 2.2.0
- Library version: 1.9.0
- Kotlin platforms: JVM
- Gradle version: tested with 8.13
Metadata
Metadata
Assignees
Labels
No labels