Skip to content

Instantly share code, notes, and snippets.

@shafty023
Created June 10, 2020 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shafty023/4bde8c28f63693937d10e4490761143f to your computer and use it in GitHub Desktop.
Save shafty023/4bde8c28f63693937d10e4490761143f to your computer and use it in GitHub Desktop.
GsonUtils
/**
* 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