Moshi: LocalDateTime adapter with multiple format

Created on 10 Apr 2018  路  7Comments  路  Source: square/moshi

By default, LocalDateTime is converted to
{"date":{"day":10,"month":4,"year":2018},"time":{"hour":3,"minute":34,"nano":115000000,"second":18}}

I can write an adapter to support ISO date string 2018-04-10T03:45:26.009

class LocalDateTimeAdapter {
    @ToJson
    fun toJson(value: LocalDateTime): String {
        return FORMATTER.format(value)
    }

    @FromJson
    fun fromJson(value: String): LocalDateTime {
        return FORMATTER.parse(value, LocalDateTime.FROM)
    }

    companion object {
        private val FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME
    }
}

How can I write an adapter which can support both format

  • {"date":{"day":10,"month":4,"year":2018},"time":{"hour":3,"minute":34,"nano":115000000,"second":18}}
  • 2018-04-10T03:45:26.009

Most helpful comment

A custom adapter is _always_ required for types that you do not control.

All 7 comments

If you know which places have which format, you can differentiate your types with JsonQualifiers. If you don't know which format might come in from the JSON, you might just have to try-catch on the parse call.

Please ask usage questions on Stack Overflow, as this issue tracker is for bugs and feature requests. More volunteers can help there.
stackoverflow.com/questions/tagged/moshi

Noted. I posted the question at
https://stackoverflow.com/questions/49750743/moshi-localdatetime-adapter-with-multiple-format

PS: I am curious how Moshi internally perform toJson/fromJson for LocalDateTime

Moshi will not serialize a type in java.* by default. You must have something registered which is outputting that format.

luaz is using ThreeTenAB (not java.*), so that's why it is also working "by default" as {"date":{"day":10,"month":4,"year":2018},"time":{"hour":3,"minute":34,"nano":115000000,"second":18}}.

Ah. Scary!

An interesting note is both Moshi and Gson produce the same result for ThreeTenABP.LocalDateTime

BTW, is the "by default" toJson/fromJson for ThreeTenABP.LocalDateTime reliable in the long run? Or it's recommended to write a custom adapter to handle ThreeTenABP.LocalDateTime?

A custom adapter is _always_ required for types that you do not control.

Was this page helpful?
0 / 5 - 0 ratings