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

2

16

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?

Sidesaddle answered 10/9, 2020 at 8:57 Comment(0)
S
41

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)
Sidesaddle answered 10/9, 2020 at 8:57 Comment(1)
The documentation is here github.com/Kotlin/kotlinx.serialization/blob/master/docs/…Raffaello
I
1

We can partially decode JSON with required keys using using keyword : ignoreUnknownKeys

fun create(): NetworkService {
        return NetworkServiceImpl(
            client = HttpClient(Android) {
                install(Logging) {
                    level = LogLevel.ALL
                }
                install(JsonFeature) {
                    serializer = KotlinxSerializer(
                        json = kotlinx.serialization.json.Json {
                            isLenient = true
                            ignoreUnknownKeys = true
                        })
                }
            }
        )
  }
Incomprehensive answered 5/5, 2023 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.