Ignore parse exceptions for kotlinx-serialization
1 min readApr 8, 2019
The problem is how to ignore the parse exceptions if the property is nullable, for example:
@Serializable
data class Data(a: Int = 0, b: Int? = null)val data = Json.parse(Data.serializer(), "{a: 1, b: 2.0}") // throws NumberFormatException
We expected the
// No exception
assertThat(data.a).isEqualTo(1)
assertThat(data.b).isNull()
kotlinx-serialization parsing is in strict mode by default.
Even we disabled it, it doesn’t work on this case. So we decided to implement it by ourselves to throw nothing if strictMode
disabled.
Installation:
repositories {
maven { url "https://jitpack.io" }
}dependencies {
implementation 'com.github.yongjhih.kotlinx-serialization:kotlinx-serialization-runtime:13496cbef6'
}
So now:
val data = Json.nonstrict.parse(Data.serializer(), "{a: 1, b: 2.0}") // No NumberFormatException
Bonus — Error Handler
val data = Json(errorHandler = { e -> e.printStackTrace() }).parse(Data.serializer(), "{a: 1, b: 2.0}") // printStackTrace() for any exception whenever throwing
Implementation:
| single<Converter.Factory> {
| Json(strictMode = false,
| - encodeDefaults = false).asConverterFactory(MediaType.get("application/json"))
| + encodeDefaults = false,
| + errorHandler = { e ->
| + Timber.e(e)
| + }).asConverterFactory(MediaType.get("application/json"))
| }