问题
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:
- The
obj
is an instance ofArrayList<MyClass>
- I'm using
implementation 'com.google.code.gson:gson:2.8.5'
- I'm using
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
回答1:
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.
回答2:
Apparently the toString()
method inside the parsed class is needed to make the Gson library work.
I don't know why but if you know it you feel free to respond!
Adding the toString()
method is a little trick to add information to the release version. You should follow the correct way on how to do it and add pro-guard rules.
@Override
public String toString() {
return "MyClass{" +
"a='" + a + '\'' +
", b='" + b + '\'' +
", c='" + c + '\'' +
", d='" + d + '\'' +
'}';
}
回答3:
You need to @Expose
instend of @SerializedName
@Expose
public String a;
来源:https://stackoverflow.com/questions/58974728/gson-parsing-problem-with-release-version-incorrect-string-is-returned