This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

Simple records.

When working with Gson, we often need to use TypeToken to parse generic nested data, and then extract repetitive code into functions.

Entity class:

class Entity<T{
    var type: Int = 0
    var data: T? = null
}
Copy the code

Put generics in typeToken:

fun <T> convertJson(json: String): T? {
   return try {
       val typeToken =
           object: TypeToken<Entity<T>>(){}.type
       Gson().fromJson<Entity<T>>(json, typeToken).data
  } catch (e: java.lang.Exception) {
       null}}Copy the code

But the actual parsing fails:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to XXX

The reason is that when TypeToken uses generics, the generics need to be of a certain type. To the use of TypeToken. GetParameterized () function to obtain the type object.

fun <T> convertJson(json: String, t: Class<T>): T? {
   return try {
       val typeToken =
           TypeToken.getParameterized(Entity::class.java, t).type
       Gson().fromJson<Entity<T>>(json, typeToken).data
  } catch (e: java.lang.Exception) {
       null}}Copy the code

The use of TypeToken. GetParameterized () can solve the problem of abnormal gson analytical. The function needs to pass an extra argument, the class object of T.

We can simplify the function here by using the reified keyword:

inline fun <reified T> convertJson(json: String): T? {
    return try {
        val typeToken =
            TypeToken.getParameterized(Entity::class.java, T::class.java).type
        Gson().fromJson<Entity<T>>(json, typeToken).data
    } catch (e: java.lang.Exception) {
        null}}Copy the code

The reified keyword and inline keyword cannot be omitted.

Cannot use ‘T’ as reified type parameter. Use a class instead.

Omit inline, prompt:

Only type parameters of inline functions can be reified.

Because it is an inline function, the function body should not be too long, the logic is not easy to be too complex.

We welcome correction where inappropriate.