Hi Folks, I'm struggling to de-serialise a `data...
# announcements
t
Hi Folks, I'm struggling to de-serialise a
data class
object from Google's Firestore. I can save my data class (lets call it Parent) to Firestore, but on retrieval it is a HashMap which seems nontrivial to convert back because some values on Parent are themselves data classes:
Copy code
data class Parent(val id: String, val child1: Child1, ...)

data class Child1(val name: String)
I can't use GCP's DocumentSnapshot.toObject(Parent::java.class) because for that to work, every field on Parent needs to be nullable, and I'd have to recursively create nullable data class intermediaries (i.e., NullableChild1, etc) ... any suggestions on a better approach? I'm new to Kotlin so figure I'm missing something obvious here 🤷 Example code:
Copy code
// What i'd like to do

fun getFromFirestore(id): Parent {
   ...
   val data = doc.data()
   data.toObject(Parent::java.class) // this throws because it needs a 0 argument constructor to unpack the hash map into
}

// Overly complex solution

fun getFromFirestore(id): Parent {
   ...
   val data = doc.data()
   data.toObject(NullableParent::java.class) // this throws because it needs a 0 argument constructor to unpack the hash map into
}

data class NullableParent(val id: String?, val child1: Child1?, ...) {
   constructor(): this(null, null) // I could also unpack the hash map here but then this constructor gets verbose!
 
   fun toParent(): Parent {
      if(id == null || child1 == null...) throw Error("blah")
  
      return Parent(id, child1, ...) // this doesn't work because Child1 doesn't have a 0 argument constructor so I'd have to create a NullableChild now 😢
 }
}
t
Have you attempted to assign default values to all the fields in the data class?
t
I have not but will try tomorrow. Thanks for the suggestion
c
You can also try no-arg kotlin compiler plugin