Home > Software engineering >  Json Serialization error expected start of the array "[" but had EOF instead
Json Serialization error expected start of the array "[" but had EOF instead

Time:03-26

I am currently learning Kotlin Multiplatform and i'm trying to serialize a Json using the ktor Framework. I receive the JSON from the following api: https://opentdb.com/api.php?amount=10 But i am getting this error: "error: Expected start of the array "\[" but had "EOF" instead. JSON input: .....answers":\["Patrick Swayze","John Cusack","Harrison Ford"\]}\]}" The JSON i receive looks something like this: { "response_code": 0, "results": [ { "category": "Entertainment: Film", "type": "multiple", "difficulty": "easy", "question": "What breed of dog was Marley in the film "Marley & Me" (2008)?", "correct_answer": "Labrador Retriever", "incorrect_answers": [ "Golden Retriever", "Dalmatian", "Shiba Inu" ] }, { "category": "Entertainment: Comics", "type": "multiple", "difficulty": "hard", "question": "In the Batman comics, by what other name is the villain Dr. Jonathan Crane known?", "correct_answer": "Scarecrow", "incorrect_answers": [ "Bane", "Calendar Man", "Clayface" ] }, { "category": "Entertainment: Film", "type": "boolean", "difficulty": "easy", "question": "Han Solo's co-pilot and best friend, "Chewbacca", is an Ewok.", "correct_answer": "False", "incorrect_answers": [ "True" ] } ] }

This is what my code looks like `@Serializable data class Hello( val category: String, val type: Boolean, val difficulty: String, val question: String, val correctAnswer: String, val falseAnswer: String )

class KtorClient {

private val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
            prettyPrint = true
            isLenient = true
            ignoreUnknownKeys = true
        })
    }
}

@Throws(Exception::class)
suspend fun returnTestData(): String {
    return getTestData().random().question
}

private suspend fun getTestData(): List<Hello> {
    return client.get("https://opentdb.com/api.php?amount=10")
}

}`

What am i doing wrong? Thanks in Advance for the answers.

CodePudding user response:

Your data models should be like below.

data class Response(
    val response_code: Int?,
    val results: List<Result>?
)
data class Result(
    val category: String?,
    val correct_answer: String?,
    val difficulty: String?,
    val incorrect_answers: List<String>?,
    val question: String?,
    val type: String?
)
private suspend fun getTestData():Response {
    return client.get("https://opentdb.com/api.php?amount=10")
}

And also, if you want to set your own name for each field you can set @SerializedName("Field Name") on each field.

  • Related