Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.