Gson deserialize null pointer in released apk

安稳与你 提交于 2019-11-30 03:45:59

You have ProGuard enabled in your release build type - minifyEnabled true. It obfuscates the code by changing class/variable names.

You should annotate your class properties, so Gson knows what to look for:

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;
}

This way Gson won't look at the properties' names, but will look at @SerializedName annotation.

You can either use @SerializedName as mentioned by @Egor N or you may add the Gson classes to the proguard-rules.pro by using

-keep class com.packageName.yourGsonClassName

The latter has the following advantages over the former:

  • when writing your code you can put all your Gson class in a folder and keep all of them from obfuscation using the following, which saves a lot of coding:

    -keep class com.packageName.gsonFolder.** { *; }
    
  • Adding @SerializedName to each field in Gson classes is not only time-consuming especially in large projects with lots of Gson files but also increases the possibility of mistakes entering the code, if the argument in the @SerializedName is different from the field name.

  • If any other methods, such as getter or setter methods are used in the Gson class, they may also get obfuscated. Not using @SerializedName for these methods causes crash in runtime due to conflict in names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!