Search code examples
kotlincastingdata-class

String Casting to Data Class with Kotlin


I have data class. I have inserting the room database this data class. it has string type. But I want to use back. I have calling the data. It has string. But I want to convert the data class type.

How can do this ?

Edit I used the Type Conveter for Room Database. if u have same problem. u should the this example. https://medium.com/@rasim0042/type-converter-for-room-db-2700e968a6d5


Solution

  • If you want to use Gson with kotlin extension

    Extension function

    inline fun <reified T : Any> String.toDataClass(): T =
        Gson().fromJson(this, T::class.java)
    
    inline fun <reified T : Any> T.toJsonString(): String =
        Gson().toJson(this)
    

    Use to convert string and visaversa

    // to get String from DataClass object
    val jsonString: String = note.toJsonString()
    
    // to get DataClass object from String
    val note = jsonString.toDataClass<Note>()