Last active
August 19, 2021 16:55
-
-
Save erickvieira/b7667a0697c27ae469e0cbf39bf13ca2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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