Philipp Mayer
02/14/2023, 3:24 PM@JsonSerializable
data class Reminder(
val createdAt: LocalDateTime, // < this is kotlinx.datetime.LocalDateTime
val task: String,
val dueAt: LocalDateTime, // < this is kotlinx.datetime.LocalDateTime
)
I’m not sure how to indicate to Kotshi that it should also generate a Factory for this type.
I also tried creating my own adapter, but without luck:
object LocalDateTimeAdapter : JsonAdapter<LocalDateTime>() {
override fun fromJson(reader: JsonReader): LocalDateTime =
LocalDateTime.parse(reader.readJsonValue().toString())
override fun toJson(writer: JsonWriter, value: LocalDateTime?) {
writer.jsonValue(value.toString())
}
}
@OptIn(ExperimentalStdlibApi::class)
@Suppress("unused")
object MoshiWithKotshi : ConfigurableMoshi(
Moshi.Builder()
.add(LocalDateTimeAdapter) //<<<
.add(ApplicationJsonAdapterFactory)
.asConfigurable()
.done()
)
Error:
Platform class kotlinx.datetime.LocalDateTime requires explicit JsonAdapter to be registered
for class kotlinx.datetime.LocalDateTime createdAt
for class com.p10r.Reminder
Thanks in advance!Philipp Mayer
02/14/2023, 3:42 PMval reminderLens = Body.auto<List<Reminder>>().toLens()
Moving this to a wrapper object
val reminderLens = Body.auto<Reminders>().toLens()
helped here.Andrew O'Hara
02/14/2023, 4:08 PMArray
rather than List
. But your wrapper should work too. The issue is documented, but not always obvious.Andrew O'Hara
02/14/2023, 4:09 PMBody.auto
import is annoying, you can do Moshi.autoBody
or MyMoshi.autoBody
insteaddave
02/14/2023, 10:05 PMPhilipp Mayer
02/14/2023, 10:50 PMWith Moshi, you need to use Array rather than List. But your wrapper should work too. The issue is documented, but not always obvious.Thanks, I also found a Github issue that mentioned this. I’m fine with having that in mind, but it might be hard to grasp when onboarding other coworkers. 🙂
Philipp Mayer
02/14/2023, 10:52 PMQq - what was the reason behind using the kotlinx date times?Fair question! We’re running a hackathon at work and built a Kotlin Multiplatform project which shares the Request model. We just reached for kotlinx.datetime for its multiplatform support. Besides that I agree though - it feels like one can’t really count on Jetbrains when it comes to libraries. Ktor and kotlinx.serialization feel really active, but datetime, io and the others feel kind of abandoned.