首页 > 解决方案 > Gson fromJson returns null after Proguard

问题描述

We are using Proguard to obfuscate our Java application. We have some POJO class where Gson is used to create this objects at runtime from json

package com.example.app;
public class AppConfiguration {

  private String name;
  private String title;
  private String details;
}

AppConfiguration configuration = new Gson().fromJson(value, AppConfiguration.class);

After obfuscation with the proguard, the configuration return null. I have used the keep option to keep the AppConfiguration, but did not help

Progarud option

-keep class com.example.app.AppConfiguration

标签: javagsonproguardobfuscation

解决方案


Gson fromJson expects the POJO class members. So we need to keep all the member variables.(without Proguard obfuscate this attributes). The following proguard keep options keeps all the attributes of the AppConfiguration

Field serialized name

@SerializedName("keyType")
String keyType;

proguard configuration

-keepclassmembers,allowobfuscation class * {
    @com.google.gson.annotations.SerializedName <fields>;
}
 

-keep,allowobfuscation @interface com.google.gson.annotations.**

If you dont have chance to change the class, you can use the following keep options

-keepclassmembers class com.example.app.AppConfiguration {
        public protected private *;
        #Keep default members & functions
        !public !protected !private *;
    }

推荐阅读