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

Deserializing into Optionals not working with @Introspected #10782

Open
cweinberger opened this issue Apr 30, 2024 · 1 comment
Open

Deserializing into Optionals not working with @Introspected #10782

cweinberger opened this issue Apr 30, 2024 · 1 comment

Comments

@cweinberger
Copy link

cweinberger commented Apr 30, 2024

Expected Behavior

When deserializing JSON into a POJO, Optionals should be handled properly to allow detecting the absence/presence of a value (as needed on PATCH endpoints for example, where you want to differentiate between null and absence of a value).

This works fine, until I add @Introspected annotation to the POJO (which is required for Validations etc as well).

Example POJO

@Introspected
data class TestPojo(
    val field1: Optional<String>? = null,
    val field2: Optional<String>? = null
)

JSON

val output1 = objectMapper.readValue("{\"field1\": \"value1\", \"field2\": \"value2\"}", TestPojo::class.java)
val output2 = objectMapper.readValue("{\"field1\": null, \"field2\": \"value2\"}", TestPojo::class.java)
val output3 = objectMapper.readValue("{}", TestPojo::class.java)

Output

assert(output1.field1?.get() == "value1")
assert(output1.field2?.get() == "value2")

assert(output2.field1!!.isEmpty)
assert(output2.field2?.get() == "value2")

assert(output3.field1 == null)
assert(output3.field2 == null)

Actual Behaviour

When @Introspected is not used on the POJO, all is fine; however, when adding @Introspected to the POJO, both null and absent values are mapped to Optional.empty()

Output

assert(output1.field1?.get() == "value1") //
assert(output1.field2?.get() == "value2") //

assert(output2.field1!!.isEmpty) //
assert(output2.field2?.get() == "value2") //

assert(output3.field1 == null) // ❌ - Optional.empty()
assert(output3.field2 == null) // ❌ - Optional.empty()

Steps To Reproduce

I added tests in the linked sample project (DemoTest.kt)

Environment Information

macOS 14.4.1
JDK 17

Example Application

https://github.com/cweinberger/micronaut-optionals-introspected-demo

Version

4.3.6

@sdelamo
Copy link
Collaborator

sdelamo commented May 3, 2024

@cweinberger if you are using Micronaut Jackson Databind you could use https://github.com/OpenAPITools/jackson-databind-nullable for supporting thing such as JSON Merge Patch

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

No branches or pull requests

2 participants