在我的代码中,我使用方法是:
public synchronized <T> T parseJson(String json, Class<T> classOfT) throws Exception{ T target = null; Gson gson = new Gson(); target = gson.fromJson(json, classOfT); return target; }
之后在我的Activity中使用方式是:
String addModel = JsonParse.getJsonParse().parseJson(jsonString, AddModel.class); //其中AddModel是自己写的一个model类 //jsonString是一个本地文件,以Json格式存在
之后一般编译没问题,但是混淆编译就会报错:
shortMsg:java.lang.ClassCastException
longMsg:java.lang.ClassCastException: com.google.gson.internal.StringMap
stackTrace:java.lang.ClassCastException: com.google.gson.internal.StringMap
at com.android.xxxx.activity.Info.c(Unknown Source)
at com.android.xxxx.activity.Info.onClick(Unknown Source)
at android.view.View.performClick(View.java:2486)
at android.view.View$PerformClick.run(View.java:9130)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
这是由于用到Gson的反射解析json字符串,混淆后导致Model的成员变量改变而导致成员变量名不能和json字符串对应而造成的
解决方法:
在proguard.cfg文件中
首先声明不要混淆对应的Model类
如,我用到的叫AddModel:
-keep public class com.android.chebaob.model.AddModel{ *; }
而且要在proguard.cfg文件最后添加:
##---------------Begin: proguard configuration for Gson ---------- # Gson uses generic type information stored in a class file when working with fields. Proguard # removes such information by default, so configure it to keep all of it. -keepattributes Signature # For using GSON @Expose annotation -keepattributes *Annotation* # 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 com.google.gson.examples.android.model.** { *; } ##---------------End: proguard configuration for Gson ----------
这样就能解决问题了
Android混淆编译时,用到gson-2.2.2.jar进行反射解析json数据时,报ClassCastException错误