最近在自己项目中遇到一个问题,定义了多个model用于gson解析服务端返回的json格式数据。在release版本混淆了这些model导致在运行后直接崩溃,后面网上查了一些资料发现是因为model被混下了,导致gson解析无法找到对应的model里面的字段。
分析如下:
- -proguard-project.txt
- ##---------------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
- # Gson specific classes
- -keep class com.google.gson.stream.** { *; }
- # Application classes that will be serialized/deserialized over Gson
- -keep class com.google.gson.examples.android.model.** { *; }
- #这段话的意思是说,将com.google.gson.examples.android.model这个包下面的所有类
- #不进行混淆。很关键!!!!其实,只要将
- #java bean即android客户端的需要用gson进行解析的类给注释掉,不进行混淆编译既可以。
- ##---------------End: proguard configuration for Gson ----------
总结:问题主要是使用了混淆编译的方式进行apk打包(其中不混淆编译进行apk打包则一切正常),因为客户端代码中的JavaBean(实体类)的字段名称必须与服务端返回json字符串中的key要一致,才能进行解析,而混淆编译之后,客户端代码中的JavaBean(实体类)的类名与其字段名称全部变成了a、b、c、d等等字符串,这与服务端返回的json字符串中的key不一致,导致解析失败。所以,解决的办法是:在进行混淆编译进行打包apk的时候,过滤掉存放所有JavaBean(实体类)的包不进行混淆编译。