Skip to content

Instantly share code, notes, and snippets.

@erickvieira
Last active August 19, 2021 16:55
Show Gist options
  • Save erickvieira/b7667a0697c27ae469e0cbf39bf13ca2 to your computer and use it in GitHub Desktop.
Save erickvieira/b7667a0697c27ae469e0cbf39bf13ca2 to your computer and use it in GitHub Desktop.
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
inline fun <I, reified O> I?.convert(): O? = this?.let { input ->
try {
Gson().let { gson ->
gson.toJson(input).let { output ->
gson.fromJson(output, object : TypeToken<O>() {}.type)
}
}
} catch (_: Exception) {
null
} catch (_: Error) {
null
}
}
fun <T> T?.asUntypedMap(): Map<String, Any> = convert() ?: mapOf()
data class SomeDTO(
val foo: Int = 30,
val bar: String = "lorem ipsum"
)
fun main() {
val someDTO = SomeDTO()
val map = someDTO.asUntypedMap()
print(map["foo"]) // 30
print(map["bar"]) // lorem ipsum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment