Created
June 10, 2020 00:35
-
-
Save shafty023/4bde8c28f63693937d10e4490761143f to your computer and use it in GitHub Desktop.
GsonUtils
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
/** | |
* A factory that can serialize/deserialize json. | |
*/ | |
object GsonUtils { | |
/** | |
* Handles deserializing the json string into a [T] instance. | |
* | |
* @param json the json to deserialize into an instance of [T] | |
* @throws JsonSyntaxException if there is a failure deserializing then this exception is thrown | |
*/ | |
@Throws(JsonSyntaxException::class) | |
inline fun <reified T> deserialize(json: String?): T? { | |
return if (json.isNullOrBlank()) { | |
null | |
} else { | |
Gson().fromJson(json, object : TypeToken<T>() {}.type) | |
} | |
} | |
/** | |
* Handles serializing the [T] instance to a json string. | |
* | |
* @param data the object instance to serialize | |
*/ | |
fun <T : Any> serialize(data: T) = Gson().toJson(data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment