kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead

kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead

I can’t wrap my head around this exception and how to get rid of it… Anyone spot the cause because I don’t? :expressionless:

For anyone adventurous, reproduceable with:

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable
// and whatever else extra your app needs...

@Serializable
data class TargetInfo(
    val name: String,
    val id: String,
    val avgNumScans: Int,
    val rewardPerScan: String,
    val endo: Endo,
    val notes: String,
    val research: Int,
    val missions: List<MissionIdent> )

@Serializable
data class MissionIdent(val mission: String)

@Serializable
data class Endo(
    val klass: String,
    val low: Int,
    val med: Int,
    val hi: Int )

// ...
{   val str = """[{"name":"ancient disruptor",
                  "id":"hunt_ancD",
                  "avgNumScans":4,
                  "rewardPerScan":"2538+(30*lvl)",
                  "endo":{"klass":"default","low":400,"med":560,"hi":800},
                  "notes":"",
                  "research":0,
                  "missions":[{"mission":"tikal"},{"mission":"terminus"},{"mission":"isos"}]
                }]"""
    Json.decodeFromString<TargetInfo>(str)
                    .also { tInfo ->
                        // do stuff with resulting TargetInfo...
                    }
            }
///...
1 Like

facedesk … right. The whole thing was one object within an array… Solved. But leaving this here anyway if someone else bumps head to something similar with coffee-less cotton eyes.

5 Likes

Thank you very much for leaving this here. Had the same problem and you saved my day (and maybe weekend as it’s Friday).

3 Likes

I experienced the same issue during testing on Ktor Server.

fun testFun() = testApplication { ....
val response = client.get("/boruto/heroes")
val actual = Json.decodeFromString<ApiResponse>(response.content.toString())
....
}

The issue was that I was using this content instead of body.

val actual = Json.decodeFromString<T>(response.content.toString())

I changed it to this and the test passed
val actual = Json.decodeFromString<T>(response.body())

I think the error message can be improved here. The serializer expects a single Item and the Json is starting with ‘[’ which points out that this is a list of objects. Will look if there’s an issue for this or not.