使用 jackson 对象映射器从 JSON 反序列化具有长键的映射时,长键将被反序列化为字符串

问题描述 投票:0回答:1
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 但失败了。我该如何修复它?

java json kotlin jackson objectmapper
1个回答
0
投票

使用类型引用指定映射键类型:

val map: Map<Long, String> = objectMapper.readValue(
    """{"1":"a","2":b"}""",
    jacksonTypeRef(),
)

val map = objectMapper.readValue(
    """{"1":"a","2":b"}""",
    jacksonTypeRef<Map<Long, String>>(),
)
© www.soinside.com 2019 - 2024. All rights reserved.