jsonkotlindeserializationretrofit2

How to configure ignoreUnknownKeys for Kotlin Retrofit2 deserialization converter


I want to deserialize some complex json which has lots of optional keys, in Kotlin. I'm using Retrofit2.

I only care about a small subset of the available keys, so rather than trying to rigorously define data classes to work with all the possible json inputs, I'd just like to ignore unknown keys and define the parts I care about. I'm building a Retrofit factory to create my deserializer as follows:

private val retrofit = Retrofit.Builder()
        .addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
        .baseUrl(baseUrl)
        .build()

how can I configure that converter in such a way that Json is parsing using ignoreUnknownKeys=true behavior (or visa-versa, if that's the default)?


Solution

  • Have you tried providing customized Json instance?

    private val retroJson = Json { ignoreUnknownKeys = true }
    private val retrofit = Retrofit.Builder()
            .addConverterFactory(retroJson.asConverterFactory("application/json".toMediaType()))
            .baseUrl(baseUrl)
            .build()
    

    Explanation: It might be slightly confusing without at least peeking at the source code but using Json.asConverterFactory(...) is equivalent to Json.Default.asConverterFactory(...).

    This is because Jsons companion object by itself is an implementation of Json (a default one) and not a host of "static" methods.