Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
Duncan Luk Avatar asked Dec 02 '25 08:12

Duncan Luk


1 Answers

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)
like image 148
Duncan Luk Avatar answered Dec 03 '25 23:12

Duncan Luk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!