Convert Java/Kotlin object to another object using Gson
Kotlin is awesome 😎
When there are two objects with the same serializable parameters if you want to convert or deep copy the object into another one use the below GSON extension function using Kotlin to achieve this.
fun <T> Any.convert(classOfT: Class<T>): T = Gson().fromJson(Gson().toJson(this), classOfT)
Usage of the above method
Let’s say you have two classes as below that you need to convert from one to another.
class User(val name: String)class SystemUser(val name: String)
In this case, you have two objects with the same parameters in your Kotlin/Java classes but you need to convert one to another.
val user : User = User("Alien")val systemUser = user.convert(SystemUser::class.java)
That’s it you’ve made an easy way of converting/mapping an object to another object using Kotlin.