Search code examples
jsonkotlinserializationkotlinx.serialization

How to partially decode a JSON string using kotlinx.serialization?


I have a JSON string that looks like {"code": "FOO"}.

Now I want to deserialize this string using kotlinx.serialization. I've tried the following:

import kotlinx.serialization.*

@Serializable
data class Result(val code: String?)

val decoded = Json.decodeFromString<Result>(jsonString)

This works when the JSON only contains a code, but in reality there can be other keys inside the JSON string (this is out of my control). I only care about the code key, but when there are other keys present my app crashes.

How do I only decode the relevant JSON keys?


Solution

  • After debugging my app further I found the following error:

    JsonDecodingException: Unexpected JSON token at offset 14: Encountered an unknown key 'error'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys. JSON input: {"code":"FOO","otherKey":"Something else"}

    I couldn't find any documentation on this, but I managed to solve this by changing my code to the following:

    import kotlinx.serialization.*
    
    @Serializable
    data class Result(val code: String?)
    
    val decoded = Json { ignoreUnknownKeys = true }.decodeFromString<ErrorResponse>(jsonString)