使用Gson了的,在发布包时,如果需要对包进行混淆,那么必须加入如下配置
这里有一点比较坑爹,从google android_proguard_example 的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 ----------
这是google官方的proguard的文档,请注意倒数第二行,class 后方到**签名的 这一段包名应该是你所有的java bean 定义的目录(所以自己在写代码时,应该把java bean 单独放在一个包中)。
另外附上,
1.Serializable 的配置
# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
-keepclassmembers class * implements java.io.Serializable {static final long serialVersionUID;private static final java.io.ObjectStreamField[] serialPersistentFields;private void writeObject(java.io.ObjectOutputStream);private void readObject(java.io.ObjectInputStream);java.lang.Object writeReplace();java.lang.Object readResolve();
}-keep public class * implements java.io.Serializable {*;}
2.可以在proguard中 强制使所有混淆失效
-dontobfuscate
-dontoptimize
转载:http://blog.sina.com.cn/s/blog_4e1e357d0101ednf.html
解决android使用gson解析json字符串,并使用混淆编译方式打包apk遇到的问题方法一:Gson gson = new Gson();// 将json格式字符串转化为List<对象>Type listType = new TypeToken<ArrayList<PersonMsgMini>>(){}.getType();personMsgList = gson.fromJson(jsonObject.getString("list"), listType);方法二:public class AttendanceMsgGson{//字段名要跟json字符串中的key一致private ArrayList<AttendanceMsg> list;public ArrayList<AttendanceMsg> getList(){return list;}public void setList(ArrayList<AttendanceMsg> list){this.list = list;}}Gson gson = new Gson();AttendanceMsgGson attGson = gson.fromJson(result, AttendanceMsgGson.class);下面是重点:说明:其中两种gson解析json字符串的方法都没有问题,问题主要是使用了混淆编译的方式进行apk打包(其中不混淆编译进行apk打包则一切正常),因为客户端代码中的 JavaBean(实体类)的字段名称必须与服务端返回json字符串中的key要一致,才能进行解析,而混淆编译之后,客户端代码中的JavaBean(实体类)的类名与其字段名称全部变成了a、b、c、d等等字符串,这与服务端返回的json字符串中的key不一致,导致解析失败。所以,解决的办法是:在进行混淆编译进行打包apk的时候,过滤掉存放所有JavaBean(实体类)的包不进行混淆编译。经过测试,一切正常。在proguard.cfg文件中添加:# removes such information by default, so configure it to keep all of it.-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 com.google.gson.examples.android.model.** { *; }//这句非常重要,主要是滤掉 com.bgb.scan.model包下的所有.class文件不进行混淆编译-keep class com.bgb.scan.model.** {*;}