Skip to content

Proposal: Add Nullable Conversion Methods (e.g., asNullableInt) for JsonNode #4802

@JinseongHwang

Description

@JinseongHwang

Is your feature request related to a problem? Please describe.

Hi there,

It doesn't seem to provide the ability to convert a JsonNode to a nullable int(Integer).
In JsonNode.java, asInt() returns an int type and if there is no value, it returns 0 as the default value.

Describe the solution you'd like

I think it would be nice to have a method like asNullableInt() that returns an Integer that is a nullable wrapper class.
The same goes for Long, Double, and Boolean.

If you agree with me, I'd like to contribute to this project.

Usage example

I'm using it like this.
(However, this is just an example, and it would be possible to pass the nullable option as a parameter.)

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.node.ObjectNode

class FooDeserializer : JsonDeserializer<Foo>() {
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Foo {
        val node = p.codec.readTree<ObjectNode>(p)
        val someIntValue = node.get("some_int_value")?.asNullableInt()
        return Foo(someIntValue)
    }

    private fun JsonNode.asNullableInt(): Int? { // I wish this was a feature inside jackson-databind.
        return if (this.isNull) null else this.asInt()
    }
}

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    to-evaluateIssue that has been received but not yet evaluated

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions