nicopasso
02/02/2018, 1:28 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 proper objects.
Our Customer class 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?
p.s.: we've also tried to create a generic TypeConverter method by using a reified generic with inline functions but at build time, we had multiple convertion errorsgildor
02/03/2018, 5:58 AMradityagumay
02/03/2018, 12:58 PMnicopasso
02/03/2018, 4:34 PMType converters must be public. private final <T extends java.lang.Object>java.lang.String fromList(java.util.List<? extends T> list)
and
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
one for each field in the Customer objectgildor
02/03/2018, 4:55 PMnicopasso
02/03/2018, 5:20 PM@TypeConverter
public inline fun <reified T> fromList(list: List<T>?): String? {
list?.let {
val gson = Gson()
val type = object: TypeToken<List<T>>(){}.type
val json = gson.toJson(list, type)
return json
} ?: run {
return null
}
}
@TypeConverter
public inline fun <reified T> toList(json: String?): List<T>? {
json?.let {
val gson = Gson()
val type = object: TypeToken<List<T>>(){}.type
val list = gson.fromJson<List<T>>(json, type)
return list
} ?: run {
return null
}
}
nicopasso
02/03/2018, 5:21 PMgildor
02/04/2018, 2:19 AMgildor
02/04/2018, 2:44 AMdave08
02/04/2018, 3:58 AM