Jackson 对象映射器 readTree 与布尔值

问题描述 投票:0回答:1
{
   "data":{
      "id":"550e8400-e29b-41d4-a716-446655440000",
      "timestamp":"2023-05-01T16:34:16.993007076Z",
      "isProcessed":true,
      "isFailed":false
   }
}

我想使用杰克逊对象映射器反序列化它:

{
   "data":{
      "id":"550e8400-e29b-41d4-a716-446655440000",
      "timestamp":"2023-05-01T16:34:16.993007076Z",
      "isProcessed":"true",
      "isFailed":"false"
   }
}

我需要向对象映射器添加一些反序列化器吗?我的代码:

val data: JsonNode = objectMapper.readTree(logEvent)
saveData(data) // Store as jsonb
kotlin jackson objectmapper
1个回答
0
投票

一种方法是用

@JsonFormat(shape = JsonFormat.Shape.STRING)
注释布尔字段。例如:

data class Data(
    val id: UUID,
    val timestamp: OffsetDateTime,
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    val isFailed: Boolean,
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    val isProcessed: Boolean,
)

完整示例:

fun main() {
    val objectMapper = jacksonObjectMapper().registerModule(JavaTimeModule())

    val rawJson = """{
   "data":{
      "id":"550e8400-e29b-41d4-a716-446655440000",
      "timestamp":"2023-05-01T16:34:16.993007076Z",
      "isProcessed":true,
      "isFailed":false
   }
}"""

    val data = objectMapper.readValue<Response>(rawJson)

    println(objectMapper.writeValueAsString(data))
}

data class Response(val data: Data)

data class Data(
    val id: UUID,
    val timestamp: OffsetDateTime,
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    val isFailed: Boolean,
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    val isProcessed: Boolean,
)

输出:

{"data":{"id":"550e8400-e29b-41d4-a716-446655440000","timestamp":1682958856.993007076,"isFailed":"false","isProcessed":"true"}}
© www.soinside.com 2019 - 2024. All rights reserved.