Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buildJsonObject sets the Number and Boolean to null #2651

Open
blackwiz4rd opened this issue Apr 24, 2024 · 1 comment
Open

buildJsonObject sets the Number and Boolean to null #2651

blackwiz4rd opened this issue Apr 24, 2024 · 1 comment

Comments

@blackwiz4rd
Copy link

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 -> {
                        this@buildJsonObject.put(key, extras.getByte(key))
                    }

                    Short -> {
                        this@buildJsonObject.put(key, extras.getShort(key))
                    }

                    Int -> {
                        this@buildJsonObject.put(key, extras.getInt(key))
                    }

                    Long -> {
                        this@buildJsonObject.put(key, extras.getLong(key))
                    }

                    Boolean -> {
                        this@buildJsonObject.put(key, extras.getBoolean(key, false))
                    }

                    else -> {
                        this@buildJsonObject.put(key, extras.getString(key))
                    }
                }
            } ?: run {
                this@buildJsonObject.put(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
@sandwwraith
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants