Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin data class and LocalDateTime

I have Ticket class:

data class Ticket(
        var contact_email : String? = null,
        var date_opened : LocalDateTime? = null
)

but I get error during read from string:

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDateTime (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2017-11-13T06:40:00Z') at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: rnd_classifier.model.Ticket["date_opened"])

I tried add annotations without success:

data class Ticket(
        var contact_email : String? = null,

        @JsonSerialize(using = ToStringSerializer::class)
        @JsonDeserialize(using = LocalDateTimeDeserializer::class)
        var date_opened : LocalDateTime? = null
)

How to fixed it?

like image 482
mystdeim Avatar asked Mar 07 '23 02:03

mystdeim


1 Answers

Your issue is more about jackson rather than kotlin. As stated in serialize/deserialize java 8 java.time with Jackson JSON mapper

you need to add an additional gradle dependency to solve it

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.5")

after that it should work

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import org.testng.annotations.Test
import java.time.LocalDateTime

class SoTest {

    data class Ticket(
            var contact_email: String? = null,
            var date_opened: LocalDateTime? = null
    )

    @Test
    fun checkSerialize() {
        val mapper = ObjectMapper()
        mapper.registerModule(JavaTimeModule())
        val ticket = mapper.readValue(inputJsonString, Ticket::class.java)
        assert ("$ticket"=="Ticket([email protected], date_opened=2017-11-13T06:40)")
    }

    val inputJsonString = """{
        "contact_email": "[email protected]",
        "date_opened": "2017-11-13T06:40:00Z"
    }""".trimIndent()

}
like image 86
ludenus Avatar answered Mar 09 '23 19:03

ludenus