Gson图书馆和Proguard

时间:2014-04-02 05:32:35

标签: android json gson proguard

我遇到了proguard和Gson库的问题。我的代码是

AdServerResult result = (AdServerResult) new Gson().fromJson(json, 
      AdServerResult.class);

(我使用Gson库创建一个新的AdServerResult对象)

我的AdServerResult课程:

public class AdServerResult {

    public ArrayList<AdServerObject> shorts ;
    public ArrayList<AdServerObject> longs ;

    public ArrayList<AdServerObject> getShorts() {
        return shorts;
    }
    public void setShorts(ArrayList<AdServerObject> shorts) {
        this.shorts = shorts;
    }
    public ArrayList<AdServerObject> getLongs() {
        return longs;
    }
    public void setLongs(ArrayList<AdServerObject> longs) {
        this.longs = longs;
    }

    //for debug
    @Override
    public String toString(){

        StringBuilder sb = new StringBuilder() ;

        if (shorts!=null && shorts.size()>0){
            for (AdServerObject s: shorts){
                sb.append("url: "+s.getPicture_url());
            }
        }

        if (longs!=null && longs.size()>0){
            for (AdServerObject s: longs){
                sb.append("url: "+s.getPicture_url());
            }
        }

        return sb.toString();
    }

}

我的AdServerObject(出现在AdServerResult班级中):

public class AdServerObject{

    public String appli_id;
    public String picture_url;

    public String getAppli_id() {
        return appli_id;
    }
    public void setAppli_id(String appli_id) {
        this.appli_id = appli_id;
    }
    public String getPicture_url() {
        return picture_url;
    }
    public void setPicture_url(String picture_url) {
        this.picture_url = picture_url;
    }       
}

我的“json”字符串如下:

{ 
  "shorts": [
    { "appli_id": "282", "picture_url": "xxxx"},
    { "appli_id": "275", "picture_url": "xxx" }
  ], 
  "longs": [
    {"appli_id": "MyAppli3", "picture_url": "xxxxx"},
    {"appli_id": "MyAppli4", "picture_url": "xxxxx" }
  ]

}

此代码有效,但在使用proguard导出时,AdServerResult实例为null

我的proguard文件(只有json部分):

# for gson (GSON @Expose annotation)
-keep public class com.google.gson.Gson
-keepattributes *Annotation*
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
-keep class com.google.gson.examples.android.model.** { *; }

...

-keepattributes Signature
-keepattributes *Annotation*

...

-keep public class jp.xxx.ad_server.AdServerResult
-keep public class jp.xxx.ad_server.AdServerObject
-keepclassmembers class jp.xxx.ad_server.AdServerObject
-keepclassmembers class jp.xxx.ad_server.AdServerResult

我多次使用过这个Gson().fromJson但我从来没有遇到过这样的问题......我正在努力解决这个问题12个小时,我的大脑即将爆炸。

- 修改

我更新了proguard(4.11),但问题仍然存在。

1 个答案:

答案 0 :(得分:5)

您希望保留要序列化的类的字段及其原始名称:

-keepclassmembers class jp.xxx.ad_server.AdServerResult$AdServerObject { <fields>; }
-keepclassmembers class jp.xxx.ad_server.AdServerResult { <fields>; }

ProGuard可能会重命名甚至删除它们。