Created
November 4, 2020 15:40
-
-
Save bseib/329b50d242bcbdbbfcf15825741451b0 to your computer and use it in GitHub Desktop.
Distinguish nulls and non-present values with Jackson, Optional<T>, and Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package testing | |
import com.fasterxml.jackson.databind.ObjectMapper | |
import org.junit.jupiter.api.Assertions.assertEquals | |
import org.junit.jupiter.api.Test | |
import java.util.* | |
class TestJacksonWithOptional { | |
val defaultObjectMapper = ObjectMapper().apply { | |
findAndRegisterModules() | |
// jackson-datatype-jdk8 is present | |
// jackson-module-kotlin is present | |
} | |
data class Example( | |
val greeting: Optional<String>? = null | |
) | |
@Test | |
fun `handles optional type with non-null value`() { | |
val json = """{ "greeting": "hello" }""" | |
val obj = defaultObjectMapper.readValue(json, Example::class.java) | |
assertEquals("hello", obj.greeting?.get()) | |
} | |
@Test | |
fun `handles optional type with null value`() { | |
val json = """{ "greeting": null }""" | |
val obj = defaultObjectMapper.readValue(json, Example::class.java) | |
assertEquals(false, obj.greeting?.isPresent) | |
} | |
@Test | |
fun `handles optional type with non-present value`() { | |
val json = """{ }""" | |
val obj = defaultObjectMapper.readValue(json, Example::class.java) | |
assertEquals(null, obj.greeting) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This demo test code is for this stackoverflow question: https://stackoverflow.com/a/64683356/516910