0

Entity

@Entity(tableName = "words_table")
data class Word(

    @PrimaryKey
    var word: String,

    var date: String?,
    var definition: String?,
    var examples: List<String>?,
    var partOfSpeech: String?,
    var pronunciation: String?,
    var syllables: Syllables?,
    var synonyms: List<String>?
) : Serializable
data class Syllables(
    var count: Int?,
    var list: List<String>?
): Serializable

I want to store this object in database, however, I cannot figure out how would the TypeConverter for it look it. Currently, I have a TypeConverter class which converts a list into json and vice versa. That is working fine, but this Syllables object has an Int and a List. I am trying following code but this doesn't work for Syllables object

class Converters {

    @TypeConverter
    fun stringListToJson(value: List<String>?) = Gson().toJson(value)

    @TypeConverter
    fun jsonToStringList(value: String) =
        Gson().fromJson(value, Array<String>::class.java).toList()

    @TypeConverter
    fun fromSyllables(value: Syllables?) = Gson().toJson(value)

    @TypeConverter
    fun toSyllables(value: String) =
        Gson().fromJson(value, Array<Syllables>::class.java).toList()
}
Shahzad Ansari
  • 317
  • 3
  • 10

1 Answers1

0

You don't need TypeConverter for 'Syllables'. You only need for 'list'.

class Converters {

private val gSON = Gson()

@TypeConverter
fun fromList(list: List<String>?): String? {
    return if (list != null)
        gSON.toJson(list) else null
}

@TypeConverter
fun toList(s: String?): List<String>? {
    return if (s == null) arrayListOf() else {
        val listType: Type =
            object : TypeToken<List<String?>?>() {}.type
        gSON.fromJson(s, listType)
    }
}
}

and in 'Syllables'

data class Syllables(
var count: Int?,
@TypeConverters(Converters::class)
var list: List<String>?
): Serializable
imn
  • 620
  • 1
  • 7
  • 19
  • It's still giving **Cannot figure out how to save this field into database** error. I replaced my **Syllables** class with yours but it still isn't working. I also updated **Converts::class** – Shahzad Ansari Sep 07 '21 at 11:33
  • Have you added @TypeConverters(Converters::class) annotation in the database abstract class? abstract class DatabaseName : RoomDatabase() { ... – imn Sep 07 '21 at 11:53
  • Yes. TypeConverters are working fine for when it's a simple list. However, in case of this specific object, it doesn't work – Shahzad Ansari Sep 07 '21 at 12:09
  • Your question was incomplete. Why don't you try Kotlin Serialization: @ TypeConverter fun fromSyllables(syllables: Syllables?): String? = if (syllables != null) Json.encodeToString(syllables) else null @ TypeConverter fun toSyllables(s: String?): Syllables? = if (s != null) Json.decodeFromString(s) else null – imn Sep 07 '21 at 12:14