Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda