Android proguard rule for generic extension

1k views Asked by At

I have created an gson extension to serialize and de-serialize objects as below code.

/**
 * To serialize the object to json string
 */

    fun Any.toGson(): String {
        return Gson().toJson(this)
    }

/**
 * To deserialize the json string to object of type <T>
 */

    fun <T>String.toObject() : T{
        return Gson().fromJson(this, object : TypeToken<T>() {}.type)
    } 

When I build project in release mode, app is getting crashed because of proguard rules.

I have added proguard rule -keepattribute Signature. Still the app is crashing.

2020-11-24 08:47:28.448 8215-8215/? E/Paramthrowable Stacktrace Error: Throwable java.lang.AssertionError: illegal type variable reference at libcore.reflect.TypeVariableImpl.resolve(TypeVariableImpl.java:111) at libcore.reflect.TypeVariableImpl.getGenericDeclaration(TypeVariableImpl.java:125) at libcore.reflect.TypeVariableImpl.hashCode(TypeVariableImpl.java:47) at b.c.a.v.a.(TypeToken.java:9) at b.a.a.a.e.a.(ListExtension.kt:1) at o.u.u.f(ViewGroupUtilsApi14.java:11)

The above is the stack trace. ListExtension contains the code mentioned in the question Need help to resolve this issue.

2

There are 2 answers

0
Mustafo aka Shokhrukh Makmudov On

Try this in your pro-guard file

-keepattributes SourceFile,LineNumberTable

-keepattributes *Annotation*
# Do not obfuscate classes with Injected Constructors
-keepclasseswithmembernames class * { @javax.inject.Inject <init>(...); }
# Do not obfuscate classes with Injected Fields
-keepclasseswithmembernames class * { @javax.inject.Inject <fields>; }
# Do not obfuscate classes with Injected Methods
-keepclasseswithmembernames class * { @javax.inject.Inject <methods>; }

-keep class **__Factory { *; }
-keep class **__MemberInjector { *; }

# Specifies that string constants that correspond to class names should be obfuscated as well.
-adaptclassstrings com.example.your_package_name.**

0
d-feverx On
##---------------Begin: proguard configuration for Gson  ----------

-keepattributes Signature

# Gson specific classes
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
# -keep class mypersonalclass.data.model.** { *; }

add keep the rule for the model , I think your extension functions are in the model class