delblanco
11/30/2021, 8:43 AM@Test
fun test() {
val voluntary = Json.decodeFromString<SerializableVersionCheckResponse?>("""
|{
| "beheerCode": "VRIJWILLIGE_UPDATE",
| "bericht": "App moet geupdate worden"
|}
""".trimMargin()
)
assertNotNull(voluntary)
assertEquals("VRIJWILLIGE_UPDATE", voluntary.beheerCode)
val mandatory = Json.decodeFromString<SerializableVersionCheckResponse?>("""
|{
| "beheerCode": "VERPLICHTE_UPDATE",
| "bericht": "Oewe telefoon is oud."
|}
""".trimMargin())
assertNotNull(mandatory)
assertEquals("VERPLICHTE_UPDATE", mandatory.beheerCode)
val upToDate = Json.decodeFromString<SerializableVersionCheckResponse?>("")
assertNull(upToDate)
}
The last decodeFromString fails with the following message:
kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead
JSON input:
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
at kotlinx.serialization.json.internal.JsonLexer.fail(JsonLexer.kt:479)
Dominaezzz
11/30/2021, 10:28 AMDominaezzz
11/30/2021, 10:28 AMephemient
11/30/2021, 11:37 AMdecodeFromString("\"\"")
would be valid JSON string that JsonTransformingSerializer could "fix", but an empty body is not JSON. you'll have to handle that class outside of serializationdelblanco
11/30/2021, 7:54 PMobject TestSerializer : KSerializer<VersionCheckFetchResponse> {
override val descriptor: SerialDescriptor = serialDescriptor<VersionCheckFetchResponse>()
override fun serialize(encoder: Encoder, value: VersionCheckFetchResponse) = TODO()
override fun deserialize(decoder: Decoder): VersionCheckFetchResponse {
return try {
val json = (decoder as? JsonDecoder)?.decodeJsonElement() as JsonObject
val beheerCode = json["beheerCode"]?.jsonPrimitive?.content
val bericht = json["bericht"]?.jsonPrimitive?.content
VersionCheckFetchResponse(beheerCode = beheerCode, bericht = bericht)
} catch (e: Exception) {
VersionCheckFetchResponse(null, null)
}
}
}
Not liking the solution so I consider this my last resort. ATM I’m looking into response intercepting and altering under specific conditionsephemient
11/30/2021, 10:20 PMephemient
11/30/2021, 10:24 PMval value = if (string.isNotEmpty()) {
json.decodeFromString(Response.serializer(), string)
} else {
default()
}
or
val value = try {
json.decodeFromString(Response.serializer(), string)
} catch (_: SerializationException) {
default()
}
delblanco
12/01/2021, 7:37 AM