Gson在发布的apk中反序列化空指针

pad*_*eoe 19 debugging android json release gson

我正在编写一个Android应用程序需要使用gson反序列化json字符串:

{
    "reply_code": 001,
    "userinfo": {
        "username": "002",
        "userip": 003
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我创建了两个类:

public class ReturnData {
    public String reply_code;
    public userinfo userinfo;
}

public class userinfo {
    public String username;
    public String userip;
}
Run Code Online (Sandbox Code Playgroud)

最后,我在MainActivity.java中的Java代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Context context= MainActivity.this;

    //Test JSON
    String JSON="{\"reply_code\": 001,\"userinfo\": {\"username\": \"002\",\"userip\": 003}}";
    Gson gson = new Gson();
    ReturnData returnData=gson.fromJson(JSON,ReturnData.class);

    if(returnData.reply_code==null)
        Toast.makeText(context,"isNULL",Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(context,"notNULL",Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

令我困惑的是,当我调试应用程序时,它运行良好并输出"notNULL".我可以看到对象的每个属性都已正确反序列化.但是,当我从Android Studio生成发布的apk并在手机上运行apk时,它输出"isNULL",json分辨率失败!

谁能告诉我发生了什么?!

PS:的build.gradle:

apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "19.1"

defaultConfig {
    applicationId "com.padeoe.autoconnect"
    minSdkVersion 14
    targetSdkVersion 21
    versionCode 1
    versionName "2.1.4"
}
buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('src/gson-2.3.1.jar')
}
Run Code Online (Sandbox Code Playgroud)

Ego*_*uba 37

您在release构建类型中启用了ProGuard - minifyEnabled true.它通过更改类/变量名来混淆代码.

您应该注释您的类属性,以便Gson知道要查找的内容:

public class ReturnData {
    @SerializedName("reply_code")
    public String reply_code;
    @SerializedName("userinfo")
    public userinfo userinfo;
}

public class userinfo {
    @SerializedName("username")
    public String username;
    @SerializedName("userip")
    public String userip;
}
Run Code Online (Sandbox Code Playgroud)

这样Gson不会查看属性的名称,但会查看@SerializedName注释.


Ali*_*Nem 19

您可以使用@SerializedName由@Egorñ提及或可能添加GSON类的proguard-rules.pro使用

-keep class com.packageName.yourGsonClassName
Run Code Online (Sandbox Code Playgroud)

后者比前者具有以下优点:

  • 在编写代码时,您可以将所有Gson类放在一个文件夹中,并使用以下代码保持所有这些代码混淆,这样可以节省大量代码:

    -keep class com.packageName.gsonFolder.** { *; }
    
    Run Code Online (Sandbox Code Playgroud)
  • 添加@SerializedName到Gson类中的每个字段不仅耗时,特别是在具有大量Gson文件的大型项目中,而且如果参数中的参数@SerializedName与字段名称不同,也会增加错误输入代码的可能性.

  • 如果在Gson类中使用任何其他方法(如getter或setter方法),它们也可能会被混淆.@SerializedName由于名称冲突,不使用这些方法会导致运行时崩溃.