Search code examples
androidkotlintypeconverter

How to modify the TypeConverter so I can parse complex data in Room with kotlin


I have a data object like this one, that I use to save data into a column in Room.

data class MyObject(val list1: List<String>)

So if the data Class has this data MyObject(listOf(“A”,”B”,”C”))

The data for that column will be saved like this in column #1

enter image description here

Now I need to add data to that object and therefore to the column, new object looks like this

data class MyObject(val list1: List<String>,
                         val list2: List<String>,
                         val list3: List<String>,
                         val isEnabled: Boolean,
                         val isDone: Boolean)

I don´t know how to modify the TypeConverter so I can parse complex data, current Converter is this

class MyObjectConverter {

    @TypeConverter
    fun stringToMyObject (value: String?): MyObject? {
        return value?.let {
            MyObject (it.split(","))
        }
    }

    @TypeConverter
    fun myObjectToString(myObject: MyObject?): String? {
        return myObject?.value?.joinToString(",")
    }
}

Solution

  • The converter should be for the List<String> not for MyObject, that way room will use the converter only for the fields it can't persist out of the box. the converter would look like this:

    class MyListConverter {
    
        @TypeConverter
        fun stringToList (value: String?): List<String>? {
            return value?.split(",")
        }
    
        @TypeConverter
        fun listToString(list: List<String>?): String? {
            return list?.joinToString(",")
        }
    }
    

    use this with MyObject room entity and it would be used for the first three fields in MyObject, while the other two Boolean fields can be handled by room.