ktorio / ktor

Framework for quickly creating connected applications in Kotlin with minimal effort
https://ktor.io
Apache License 2.0
13.06k stars 1.07k forks source link

GSON deserialization with non-nullable Kotlin type #901

Open scorsi opened 5 years ago

scorsi commented 5 years ago

Ktor Version

1.0.1 but I think this bug also exists in 1.1.2

Only tested with GSON, may be Jackson is also affected.

Feedback

Already noticed in #157. The nullable Kotlin type is not taken into account by the GSON deserialization. Kotlin Data class:

data class Something(val value: String)

Data in HTTP:

{}

Result:

Something(value=null)

Actual workaround:

We have to add the nullable property on all data class fields.

Expecting result:

If any non-nullable field is not fulfilled, the deserialization should return null (or throw if <T> receiveOrNull() is not used).

e5l commented 5 years ago

Hi @scorsi, thanks for the report. It's obviously a bug and we'll fix it in the next release.

e5l commented 5 years ago

It looks like we need this done to perform the null check: https://github.com/google/gson/issues/445 You also could add zero argument constructor as a workaround.

abubics commented 5 years ago

Just fyi, also affects Jackson :)

Current workaround:

suspend inline fun <reified T : Any> ApplicationCall.safeReceiveOrNull(): T? = try {
  receiveOrNull()
} catch (e: Exception) {
  null
}
oleg-larshin commented 4 years ago

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.