kotlinx.serialization
kotlinx.serialization copied to clipboard
buildJsonObject sets the Number and Boolean to null
Describe the bug
The function below sets Boolean and Numbers to null when values are put in the json object.
To Reproduce
fun Intent.convertToJsonObject() = buildJsonObject {
extras?.let { extras ->
for (key in extras.keySet()) {
SuccessData.entries.find { it.value == key }?.let { entry ->
when (entry.type) {
// numbers
Byte -> {
[email protected](key, extras.getByte(key))
}
Short -> {
[email protected](key, extras.getShort(key))
}
Int -> {
[email protected](key, extras.getInt(key))
}
Long -> {
[email protected](key, extras.getLong(key))
}
Boolean -> {
[email protected](key, extras.getBoolean(key, false))
}
else -> {
[email protected](key, extras.getString(key))
}
}
} ?: run {
[email protected](key, extras.getString(key))
}
}
}
}
Expected behavior The JsonObject should contain non null Numbers and Booleans.
Environment
- Kotlin version: 1.9.22
- Library version: 1.6.0
- Kotlin platforms: Android
- Gradle version: 8.3
Can you elaborate on what exactly is problematic here? Are you talking about the ability to write this?
buildJsonObject {
val nullBool: Boolean? = null
put("key", nullBool)
}
It is allowed by design, since it is valid for a json object to contain null values. The builder above corresponds to {"key": null} json.