https://kotlinlang.org logo
#serialization
Title
# serialization
s

smallufo

10/24/2023, 12:06 PM
Hi All, Today I encountered one strange error regarding to serialize embedded LocalDateTime field . Here is my case , I have a simple LocalDateTimeSerializer , code here https://github.com/smallufo/kotlinPlay/blob/master/serialize/src/main/java/LocalDateTimeSerializer.kt And all tests passed. And I have another data class :
Copy code
data class TimePlace(val time: LocalDateTime, val place: String)
which just embed one LocalDateTime and one String And this is the Serializer for the class : https://github.com/smallufo/kotlinPlay/blob/master/serialize/src/main/java/TimePlaceSerializer.kt As you see , I delegate LocalDateTime encoding / decoding with the LocalDateTimeSerializer . I thought it should be OK . but the two tasks just fail : source here
Copy code
private val json1 = Json {
        encodeDefaults = false
    }

    private val json2 = Json {
        serializersModule = SerializersModule {
            contextual(LocalDateTime::class, LocalDateTimeSerializer)
        }
        encodeDefaults = false
    }

    @Test
    fun test1() {
        val time = LocalDateTime.of(2023, 10, 24, 1, 50)
        val place = "New York"
        val timePlace = TimePlace(time, place)

        val serialized = json1.encodeToString(TimePlaceSerializer, timePlace)
        <http://logger.info|logger.info> { serialized }
        val deserialized = json1.decodeFromString(TimePlaceSerializer, serialized)

        assertEquals(timePlace, deserialized)
    }

    @Test
    fun test2() {
        val time = LocalDateTime.of(2023, 10, 24, 1, 50)
        val place = "New York"
        val timePlace = TimePlace(time, place)

        val serialized = json2.encodeToString(TimePlaceSerializer, timePlace)
        <http://logger.info|logger.info> { serialized }
        val deserialized = json2.decodeFromString(TimePlaceSerializer, serialized)

        assertEquals(timePlace, deserialized)
    }
No matter test1 or test2 , it throws
Copy code
java.lang.ExceptionInInitializerError
	at TimePlaceSerializerTest.test1(TimePlaceSerializerTest.kt:33)
	...
Caused by: kotlinx.serialization.SerializationException: Serializer for class 'java.time.LocalDateTime' is not found.
Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.
Even I mark the class @Serializable doesn’t help
Copy code
@Serializable
data class TimePlace(
        @Serializable(with = LocalDateTimeSerializer::class)
        val time: LocalDateTime,
        val place: String)
BTW , IntelliJ cannot run test1 and test2 at the same time , it will throw
Copy code
java.lang.NoClassDefFoundError: Could not initialize class TimePlaceSerializer
at TimePlaceSerializerTest.test2(TimePlaceSerializerTest.kt:46)
It’s a strange error (I am sure I am serializing/testing against
java.time.LocalDateTime
, not kotlin’s version) Any thing I missed ? Thanks.