2016-07-28 112 views
4

我在我的項目中使用ProGuard,但在新的Gson()。toJson(Request)中給出了錯誤的數據;ProGuard for Android和Retrofit2 Converter Gson?

我得到了放

{"username":"manage","password":"689184d4418b6d975d9a8e53105d3382","value":"10","store":"76"} 

我ProGuard的規則

-dontwarn okio.** 
-dontwarn retrofit2.Platform$Java8 
-dontwarn sun.misc.Unsafe 
-dontwarn org.w3c.dom.bootstrap.DOMImplementationRegistry 
-dontwarn retrofit2.** 
-keep class retrofit2.** { *; } 
-keepattributes Signature 
-keepattributes Exceptions 
-keepclassmembers class rx.internal.util.unsafe.** { 
    long producerIndex; 
    long consumerIndex; 
} 

-keepclasseswithmembers class * { 
    @retrofit2.http.* <methods>; 
} 
-keep class com.google.gson.** { *; } 
-keep class com.google.inject.** { *; } 

{"a":"manage","b":"689184d4418b6d975d9a8e53105d3382","c":"10","d":"76"} 

,而不是和我使用

compile 'com.squareup.retrofit2:converter-gson:2.0.0' 

是否有推薦的ProGuard配置用於retrofit2:converter-gson in Android?

+0

最簡單的將是保持你婉與GSON使用的類。否則你可能想看看gson是否有一個註釋來給一個字段命名 - 這是我在我的應用程序中使用jackson的方式。 – Dodge

+0

如何保持班級..任何規則 – praj

+0

看到我的回答:) – Dodge

回答

9

你要麼保留你正在使用的類與gson或使用@SerializedName註釋。

選項1(保留類)

 
// all classes in a package 
-keep class com.example.app.json.** { *; } 
// or a specific class 
-keep class com.example.app.json.SpecificClass { *; } 

選項2(使用@SerializedName):

 
public class YourJsonClass{ 
    @SerializedName("name") String username; 

    public MyClass(String username) { 
    this.username = username; 
    } 
} 

與第二個選項的ProGuard仍然混淆類和字段的名稱,但gosn可以使用註釋爲每個字段獲取正確的名稱

3

@Keep註釋您的JSON模型類。

0

就我而言,我使用Moshi進行JSON改造,但問題是一樣的。它在調試中起作用,但在使用ProGuard構建之後,使用該模型的RecyclerView因NullPointerException而崩潰,因爲該列表中充滿了空模型對象,因爲Moshi沒有識別出任何字段。我認爲Gson也會發生同樣的情況。

一種解決方案是標註各個領域與其對應的序列化的名字:

@Json(name="username") String username; 

這樣的ProGuard可以混淆變量名沒有打破轉換。

另一種解決方案是增加一個「保存」選項像道奇建議,在proguard-rules.pro文件

-keep public class com.example.model.User