Skip to content

Instantly share code, notes, and snippets.

@Jericho2Code
Last active December 7, 2019 20:10
Show Gist options
  • Save Jericho2Code/6bb464fedfa80fa3401ae68c25417bc8 to your computer and use it in GitHub Desktop.
Save Jericho2Code/6bb464fedfa80fa3401ae68c25417bc8 to your computer and use it in GitHub Desktop.
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