Created
May 27, 2021 06:00
-
-
Save nphausg/4e19d7226a4c7a14257fe4dc2470fe2b to your computer and use it in GitHub Desktop.
GsonExtensions.kt
This file contains hidden or 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.GsonBuilder | |
| import com.google.gson.reflect.TypeToken | |
| import java.lang.reflect.Type | |
| // region [G-SON] | |
| val gSon: Gson by lazy { GsonBuilder().disableHtmlEscaping().create() } | |
| fun Any?.toJson(): String = gSon.toJson(this) | |
| // Convert a String to an Object | |
| inline fun <reified T> String.toObject(): T { | |
| val type = typeToken<T>() | |
| return gSon.fromJson(this, type) | |
| } | |
| inline fun <reified T> typeToken(): Type = object : TypeToken<T>() {}.type | |
| // Convert a Map to an Object | |
| inline fun <reified T> Map<String, Any>.toObject(): T = convert() | |
| // Convert an object to a Map | |
| fun <T> T.toMap(): Map<String, Any> { | |
| return convert() | |
| } | |
| // Convert an object of type T to type R | |
| inline fun <T, reified R> T.convert(): R { | |
| return gSon.toJson(this).toObject() | |
| } | |
| // endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment