Leandro Borges Ferreira Leandro Borges Ferreira - 1 year ago 162
Android Question

How to deserialize ThreeTen LocalDateTime in Retrofit?

I'm trying to deserialise this class in Retrofit:

data class Measurement(val id: Long, val value: Float, val dateTime: LocalDateTime, val trashCanId: Long) : Parcelable {
companion object {
@JvmField val CREATOR: Parcelable.Creator<Measurement> = object : Parcelable.Creator<Measurement> {
override fun createFromParcel(source: Parcel): Measurement = Measurement(source)
override fun newArray(size: Int): Array<Measurement?> = arrayOfNulls(size)

constructor(source: Parcel) : this(source.readLong(), source.readFloat(), source.readSerializable() as LocalDateTime, source.readLong())

override fun describeContents() = 0

override fun writeToParcel(dest: Parcel?, flags: Int) {


As you can see, I'm using LocalDateTime, it's from ThreeTen. Well, I receive this from my server

"id": 1,
"value": 50.6,
"dateTime": {
"hour": 2,
"minute": 6,
"second": 9,
"nano": 0,
"dayOfYear": 308,
"dayOfWeek": "THURSDAY",
"month": "NOVEMBER",
"dayOfMonth": 3,
"year": 2016,
"monthValue": 11,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"

Well, but my dateTime is always Null so I believe that Retrofit doesnt know how parse the Data, or am I missing something?

Is there any good workaround?

Any help is appreciated!

Answer Source

Bsed on Manoj Frekzz answer, I found my solution...

First I created a DateTimeDto.

data class DateTimeDto(val dayOfYear : Int, val dayOfWeek : String, val month : String, val dayOfMonth : Int,
                       val year : Int, val monthValue : Int, val hour : Int, val minute : Int, val second : Int,
                       val nano : Int, val chronology : Chronology)

fun toDateTime () : LocalDateTime{
     return LocalDateTime.of(year, monthValue, dayOfMonth, hour, minute)

And I changed the signature of the interface from:


fun getLocalDateTime() : Observable<List<LocalDateTime>>



fun getLocalDateTime() : Observable<List<DateTimeDto>>

Then, in my Observer I did that:

                .map { it.map { it.toLocalDateTime() } }

And it worked just fine... It would be nicer if I Retrofit could deserialize it automatically, but this is a good workaround

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download