t3chb0t
t3chb0t

Reputation: 18685

Serialize value-types without creating additional fields for 'value' in the database

With firestore it's possible to use (data) class(es)

data class Address(var person: Person = Person("", ""))
data class Person(var firstName: String = "", var lastName: String = "")

that will be serialized into their properties like that

document:
  person:
     firstName: "John"
     lastName: "Doe"

However, I'd like to have a value-type for firstName like this one:

data class FirstName(var value: String = "") {
    init {
        // check value etc.
    }
}

but when I use it for the firstName in its default form, it'll serialize into

document:
  person:
     firstName:
        value: "John"
     lastName: "Doe"

In order to de/serialize it, I use the standard mechanism like:

// Serialize/write
firestore
   .collection("path")
   .document()
   .set(address)

// Deserialize/read e.g.
firestore
   .collection("path")
   .whereEqualTo("person.firstName", "John")
   .get()
   .await()
   .toObjects(Address::class.java)

How can I make it serialize into and deserialize from a string so that the value field is not created?

Upvotes: 1

Views: 53

Answers (1)

Greg
Greg

Reputation: 900

Ultimately it seems that the classes are serialised here, doesn't look like you're able to customise it.

Personally I think it would be more conventional and end up with simpler code if you just made the classes match the expected database schema (and convert them to DTO classes if you need a different structure somewhere else).

Upvotes: 2

Related Questions