Skip to content

Instantly share code, notes, and snippets.

@bseib
Created November 4, 2020 15:40
Show Gist options
  • Save bseib/329b50d242bcbdbbfcf15825741451b0 to your computer and use it in GitHub Desktop.
Save bseib/329b50d242bcbdbbfcf15825741451b0 to your computer and use it in GitHub Desktop.
Distinguish nulls and non-present values with Jackson, Optional<T>, and Kotlin
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)
}
}
@bseib
Copy link
Author

bseib commented Nov 8, 2020

This demo test code is for this stackoverflow question: https://stackoverflow.com/a/64683356/516910

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