sumek
sumek

Reputation: 28172

Kotlin & Jackson: type error when specifying custom serialisation for a data class field

I have a Kotlin data class that is serialised to JSON in a Spring Boot project. I'd like to customise how date is formatted when serialising to JSON. The name of the field should be serialised using default rules. That expresses what I'd like to do:

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()
)

But I get a type error:

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

I did try switching the parameter to annotation to contentUsing but the type error remained the same.

Upvotes: 2

Views: 1691

Answers (1)

DragneelFPS
DragneelFPS

Reputation: 473

Following is working for me

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")
}

Gives me output:

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

Do make sure you have the correct import for JsonSerializer

import com.fasterxml.jackson.databind.JsonSerializer

and add override marker to serialize method

Upvotes: 3

Related Questions