nicopasso
02/02/2018, 1:16 PM@Entity
data class Customer(
@PrimaryKey
var id: Int,
var name: String,
var paymentAccounts: List<PaymentAccount>,
var addresses: List<Address> )
What we want to acheive is a generic solution for TypeConverters.
This is the first not-a-100%-correct solution we came up with:
fun <T> fromList(list: T?): String? {
list?.let {
val gson = Gson()
val type = object: TypeToken<T>(){}.type
val json = gson.toJson(list, type)
return json
} ?: run {
return null
}
}
fun <T> toList(json: String?): T? {
json?.let {
val gson = Gson()
val type = object: TypeToken<T>(){}.type
val list = gson.fromJson<T>(json, type)
return list
} ?: run {
return null
}
}
@TypeConverter
fun fromPaymentAccountList(list: List<PaymentAccount>?) = fromList(list)
@TypeConverter
fun toPaymentAccountList(json: String?) = toList<List<PaymentAccount>>(json)
@TypeConverter
fun fromAddressList(list: List<Address>?) = fromList(list)
@TypeConverter
fun toAddressList(json: String?) = toList<List<Address>>(json)
With this approach we have only one big problem: no compilation errors, no other errors BUT all the properties in the data class are converted to `LinkedTreeMap`s instead of POKOs.
Our Customer object fortunately is not so complicated but we have other classes with list of objects and each object contains another list of other objects. It makes no sense to me to write a converter for each type that I want to persist with Room. Is there a solution to this problem?