Hi i've problem with the library Gson in a release version.
In practice, in the release version of my application, using the new Gson().toJson(obj)
method an incorrect string is returned.
The returned string is missing some field of my object. Is it possible that the release version needs some missing options?
Here are some useful information:
obj
is an instance of ArrayList<MyClass>
implementation 'com.google.code.gson:gson:2.8.5'
Android Studio 3.5.1
MyClass is build like this:
public class MyClass{
@SerializedName("a")
private String a;
@SerializedName("b")
private Integer b;
@SerializedName("c")
private String c;
@SerializedName("d")
private String d;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
...
}
Example:
MyClass example = new MyClass("a","b","c","d");
ArrayList<MyClass> listExample = new ArrayList<MyClass>();
listExample.add(example);
String strObj = new Gson().toJson(listExample);
Current output:
[
{
"b":"b",
"c":"c",
"d":"d",
}
]
Expected output
[
{
"a":"a",
"b":"b",
"c":"c",
"d":"d",
}
]
To reproduce the error just follow the github: https://github.com/Ciardini/error02
In release build Android compiler shrink and optimize code [see Android doc]. R8 deletes some apparently useless information, that are necessary for Gson to serialize objects correctly. To prevent R8 from stripping this info, you need to add the following code to proguard-rules.pro file:
-keep class com.giacomociardini.error02.entities.** { <fields>; }
For other details you can refer to this example on official Gson GitHub repo.