question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Json.serializersModule.plus does not work as expect

See original GitHub issue

Describe the bug Json.serializersModule.plus a new custom module report error

Mark the class as @Serializable or provide the serializer explicitly.
kotlinx.serialization.SerializationException: Serializer for class 'Date' is not found.

To Reproduce custom serializer

object DateSerializer: KSerializer<Date> {
    private val DATE_FORMATS: List<String> = listOf(
        "yyyy-MM-dd HH:mm:ss",
        "yyyy-MM-dd",
        "yyyyMMdd'T'HHmmss"
    )
    val DEFAULTOUTPUT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): Date {
        val dateStr = decoder.decodeString()
        for (dateFormat in DATE_FORMATS) {
            try {
                return SimpleDateFormat(dateFormat).parse(dateStr)
            } catch (ignore: ParseException) {
                // ignore
            }
        }
        throw SerializationException(
            "Deserializer for Date class with value ${dateStr} is not support"
        )
    }

    override fun serialize(encoder: Encoder, value: Date) {
        encoder.encodeString(DEFAULTOUTPUT.format(value))
    }
}

target object

 @Serializable
 data class DatawithDate(val haha: String, @Contextual val time: Date)

pass test

@Test
    fun `test serialize  class with date`() {
        val data = DatawithDate("haha", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-07-01 01:02:03"))
        val customModule = SerializersModule {
            contextual(DateSerializer)
        }
        val format = Json { serializersModule = customModule }
        val result = format.encodeToString(data)
        assertNotNull(result)
        //language=JSON
        assertEquals("{\"haha\":\"haha\",\"time\":\"2021-07-01 01:02:03\"}", result)
    }

failed test

@Test
    fun `test serialize  class with date`() {
        val data = DatawithDate("haha", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-07-01 01:02:03"))
        val customModule = SerializersModule {
            contextual(DateSerializer)
        }
        val format = Json {}
        format.serializersModule.plus(customModule)
        val result = format.encodeToString(data)
        assertNotNull(result)
        //language=JSON
        assertEquals("{\"haha\":\"haha\",\"time\":\"2021-07-01 01:02:03\"}", result)
    }

Expected behavior plus should enable the custom serializer for date Environment

  • Kotlin version: [1.5.20]
  • Library version: [1.2.2]
  • Kotlin platforms: [JVM]
  • Gradle version: [7.0.2]
  • IDE version (if bug is related to the IDE) [IntellijIDEA 2021.2]
  • Other relevant context [macos 10.15 jdk8]

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
sandwwraithcommented, Mar 29, 2022

@oth-libs You would need to create a new instance of Json

1reaction
shanshincommented, Aug 31, 2021

Hi! plus is a not mutating operator - it does not modify the receiver object. According to docs it Returns a combination of two serial modules. If you want to sum two different modules, you can do it in the builderAction or earlier:

    val otherModule = SerializersModule { }
    val format = Json {serializersModule = otherModule.plus(customModule)} // or serializersModule = otherModule + customModule
Read more comments on GitHub >

github_iconTop Results From Across the Web

json - kotlin: nested polymorphic serialization with generics
When deserializing, we try the supported serializers one by one (string, int, and pair of ints). I do realize that this is not...
Read more >
JsonContentPolymorphicSerializer - Kotlin
It is possible to serialize values this serializer. In that case, class discriminator property won't be added to JSON stream, i.e., deserializing a...
Read more >
Kotlinx.serialization part2 - Peter Nagy
By default kotlinx will not encode the default value(s). ... Unexpected JSON token at offset 1: Expected string literal with quotes.
Read more >
JsonUtilities.ToJson with List<string> not working as expected
Countless developer hours have been squandered discovering this completely unobvious limitation. The Unity JSON "implementation" should never ...
Read more >
PrimitiveKind - GitHub Pages
Serial descriptors for primitive kinds are not expected to have any nested elements, thus its element count should be zero. If a class...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found