I have a data class like below that has a member of type Duration:
@Serializable
data class DataClass(
val fieldOne: Long,
val fieldTwo: String,
val fieldThree: Duration,
) {
constructor() : this(0, "", Duration.ZERO, "")
}
I am working with Firebase Realtime Database to store this DataClass and am encountering an issue when I de-serialize a DataClass object.
I am seeing that even though the value held in fieldThree gets stored appropriately in Firebase Realtime Database, when de-serializing it in the application, the value is zero (0).
This happens because of the default constructor in place and I don’t understand why.
I need the default constructor or else I will get an error while de-serializing stating that a default constructor is missing from the DataClass.
I am aware that I need Kotlin 1.7.20 to be able to serialize a Duration object (reference here) and have done so in my application. I have also tried implementing the custom serializer suggested in the reference above.
All other fields are de-serialized correctly, no matter the value.
An example of an instantiation of the DataClass can be:
DataClass(12345, "", Duration.hours(1))
What am I doing wrong here?
>Solution :
The Firebase Realtime Database can only store JSON values.
The Kotlin Duration class is not a known JSON type, and a quick code search on the SDK doesn’t show any special handling for the type.
In order to store a duration in the Firebase Realtime Database, you’ll have to keep it as a supported JSON type in your data class, or handle the conversions yourself.