jvm Kotlin和Jackson:为数据类字段指定自定义序列化时出现类型错误

kcugc4gi  于 2022-11-07  发布在  Kotlin
关注(0)|答案(1)|浏览(194)

我有一个Kotlin数据类,在Sping Boot 项目中被序列化为JSON。我想定制在序列化为JSON时如何格式化日期。字段的名称应该使用默认规则序列化。这表达了我想做的事情:

class ZonedDateTimeSerialiser : JsonSerializer<ZonedDateTime>() {
    @Throws(IOException::class)
    fun serialize(value: ZonedDateTime, gen: JsonGenerator, serializers: SerializerProvider?) {
        val parseDate: String? = value.withZoneSameInstant(ZoneId.of("Europe/Warsaw"))
        .withZoneSameLocal(ZoneOffset.UTC)
            .format(DateTimeFormatter.ISO_DATE_TIME)
        gen.writeString(parseDate)
    }
}

data class OrderNotesRequest(
    @JsonSerialize(using = ZonedDateTimeSerialiser::class)
    val date: ZonedDateTime = ZonedDateTime.now()
)

但我得到一个类型错误:

Type mismatch.
Required:
KClass<out (JsonSerializer<Any!>..JsonSerializer<*>?)>
Found:
KClass<ZonedDateTimeSerialiser>

我确实尝试将注解的参数切换为contentUsing,但类型错误仍然存在。

aiazj4mn

aiazj4mn1#

以下是我的工作

object JacksonRun {
    @JvmStatic
    fun main(args: Array<String>) {
        val objMapper = ObjectMapper().apply {
            registerModule(KotlinModule())
        }
        val order = OrderNotesRequest()
        println(objMapper.writeValueAsString(order))
    }

}

data class OrderNotesRequest(
    @JsonSerialize(using = ZonedDateTimeSerialiser::class)
    val date: ZonedDateTime = ZonedDateTime.now()
)

class ZonedDateTimeSerialiser : JsonSerializer<ZonedDateTime>() {
    @Throws(IOException::class)
    override fun serialize(value: ZonedDateTime, gen: JsonGenerator, serializers: SerializerProvider?) {
        val parseDate: String = value.withZoneSameInstant(ZoneId.of("Europe/Warsaw"))
            .withZoneSameLocal(ZoneOffset.UTC)
            .format(DateTimeFormatter.ISO_DATE_TIME)
        gen.writeString(parseDate)
    }
}

build.gradle.kts:

dependencies {
    implementation("com.fasterxml.jackson.core:jackson-core:2.13.2")
    implementation("com.fasterxml.jackson.core:jackson-annotations:2.13.2")
    implementation("com.fasterxml.jackson.core:jackson-databind:2.13.2")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.0")
}

提供输出:

{"date":"2022-03-21T10:29:19.381498Z"}

请务必确保导入了正确的JsonSerializer

import com.fasterxml.jackson.databind.JsonSerializer

并将override标记添加到serialize方法

相关问题