如何在MapByteArray -> ObjectKotlin时阻止JacksonObjectMapper将字符串“null”Map为null

nkhmeac6  于 7个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(54)

嗨,我正在使用KotlinJacksonObjectMap器进行Map,遇到了一些问题,
我从一个JSON字符串开始,如下所示

{
  "name": "testName",
  "age": "null",
}

和一个看起来像这样的物体

{
val name: String,
val age: Int?
}

我想将JSON字符串反序列化到对象中,当它试图将字符串“null”Map到年龄时,它会抛出一个错误,而年龄应该是int或null。现在,JacksonMapper正在将这个“null”字符串转换为Null值,并给出下面的对象

{
"name" = "testName",
"age" = null
}

有没有一种简单的方法来配置这个Map器的行为,使它使用严格的类型,而不自动将字符串Map到它假定的字符串中?

o4hqfura

o4hqfura1#

MapperFeature.ALLOW_COERCION_OF_SCALARS。如果设置为false,它将阻止ObjectMapper将数字和布尔值的String表示形式强制转换为Java对应形式。只允许严格转换。
下面是它的用法示例

package com.stackoverflow

import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.exc.MismatchedInputException
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

data class JSON(
    val name: String,
    val age: Int?
)

class ObjectMapperTest {

    private val objectMapper =
        ObjectMapper()
            .registerKotlinModule()
            .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false)

    @Test
    fun mapStringTest() {
        assertThrows<MismatchedInputException> {
            objectMapper.readValue(
                """
            {
              "name": "testName",
              "age": "null"
            }
            """.trimIndent(),
                JSON::class.java
            )
        }

        assertThrows<MismatchedInputException> {
            objectMapper.readValue(
                """
            {
              "name": "testName",
              "age": "1"
            }
            """.trimIndent(),
                JSON::class.java
            )
        }

        assertEquals(1,  objectMapper.readValue(
            """
            {
              "name": "testName",
              "age": 1
            }
            """.trimIndent(),
            JSON::class.java
        ).age)

        assertNull(objectMapper.readValue(
            """
            {
              "name": "testName"
            }
            """.trimIndent(),
            JSON::class.java
        ).age)
    }
}

相关问题