Skip to content

decodeJsonElement incorrectly returns the full array when decoding an array element via decodeFromJsonElement #3044

@JBeet

Description

@JBeet

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions