Last active
December 7, 2019 20:10
-
-
Save Jericho2Code/6bb464fedfa80fa3401ae68c25417bc8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.arch.persistence.room.TypeConverter | |
import com.google.gson.Gson | |
import com.google.gson.reflect.TypeToken | |
import java.lang.reflect.Type | |
open class BaseConverter<T>(private val type: Class<T>) { | |
private val gson = Gson() | |
@TypeConverter | |
fun fromString(value: String?): T? = value?.let { gson.fromJson(value, type) } | |
@TypeConverter | |
fun fromClass(value: T?): String? = value?.let { gson.toJson(value) } | |
} | |
open class BaseListConverter<T>(private val type: Type) { | |
private val gson = Gson() | |
@TypeConverter | |
fun fromString(value: String?): List<T>? = value?.let { gson.fromJson(value, type) } | |
@TypeConverter | |
fun fromList(list: List<T>?): String? = list?.let { gson.toJson(list) } | |
} | |
private inline fun <reified T> type(): Type = object : TypeToken<T>() {}.type | |
// usage | |
class LocalDateConverter : BaseConverter<LocalDate>(LocalDate::class.java) | |
class LongListConverter : BaseListConverter<Long>(type<List<Long>>()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment