import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class ObjectMapperTest {
@Test
fun hello() {
val objectMapper = objectMapper()
val map: Map<Long, String> = objectMapper.readValue(objectMapper.writeValueAsString(mapOf(1L to "hi", 2L to "hello")), Map::class.java) as Map<Long, String>
assertThat(map[1L]).isEqualTo("hi")
}
private fun objectMapper(): ObjectMapper {
val objectMapper = ObjectMapper()
.registerModule(JavaTimeModule())
.registerModule(KotlinModule())
.activateDefaultTyping(
BasicPolymorphicTypeValidator.builder().allowIfBaseType(Any::class.java).build(),
ObjectMapper.DefaultTyping.EVERYTHING
)
return objectMapper
}
}
因为我已经发现 json key 必须是来自 this post 的 String 类型,但我想让这个测试代码通过。是否有任何 Jackson ObjectMapper 配置可供应用?我已经尝试了一些选项或制作自定义 KeyDeserializer 但失败了。我该如何修复它?
使用类型引用指定映射键类型:
val map: Map<Long, String> = objectMapper.readValue(
"""{"1":"a","2":b"}""",
jacksonTypeRef(),
)
或
val map = objectMapper.readValue(
"""{"1":"a","2":b"}""",
jacksonTypeRef<Map<Long, String>>(),
)