请注意,有些人可能建议我将模型类添加到 proguard -keep 中,我强调我不想这样做,由于我的雇主施加的安全限制准则,我正在寻找一种不涉及编辑 proguard 规则的解决方案
使用Gson将Json格式的字符串解析为映射到Pojo的数组,调试变体一切正常 但是在启用 proguard 的发布版本中,映射的 Pojo 对象的属性返回 null 导致应用程序崩溃,下面是 model/pojo 类:
package com.xx.xxxxxxx
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class BeneficiaryModel implements Serializable {
@SerializedName("beneficiaryId")
@Expose
private String beneficiaryId;
@SerializedName("beneficiaryName")
@Expose
private String beneficiaryName;
@SerializedName("beneficiaryType")
@Expose
private String beneficiaryType;
@SerializedName("status")
@Expose
private String status;
public String getBeneficiaryId() {
return beneficiaryId;
}
public void setBeneficiaryId(String beneficiaryId) {
this.beneficiaryId = beneficiaryId;
}
public String getBeneficiaryName() {
return beneficiaryName;
}
public void setBeneficiaryName(String beneficiaryName) {
this.beneficiaryName = beneficiaryName;
}
public String getBeneficiaryType() {
return beneficiaryType;
}
public void setBeneficiaryType(String beneficiaryType) {
this.beneficiaryType = beneficiaryType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
这就是我将 json 字符串序列化为对象数组的方法
Gson gson = new Gson();
clientes = gson.fromJson(beneficiaryStringJsonArray, BeneficiaryModel[].class);
models = new ArrayList<BeneficiaryModel>(Arrays.asList(clientes));
Log.e("TAG", models.get(0).getBeneficiaryId() + "," + models.get(0).getBeneficiaryName());
// Log returns null , null
这是 Json 字符串响应中需要序列化的部分:
[{"beneficiaryId":"XYZ54646464646","beneficiaryName":"xxxxxxxxxxxxxx1","beneficiaryType":"","status":"ACTIVE"},{"beneficiaryId":"XYZ5468524654","beneficiaryName":"xxxxxxxxxxxxx2","beneficiaryType":"","status":"ACTIVE"}]
(正如我之前提到的,在 Debug模式下一切正常)
最佳答案
我发现对我有用的唯一解决方案是使用 jackson 库,我只需向我的 proguard 添加一些规则,而无需在我的应用程序中添加模型或任何其他文件。 这是 jackson 需要的规则
# Proguard configuration for Jackson 2.x
-keep class com.fasterxml.jackson.databind.ObjectMapper {
public <methods>;
protected <methods>;
}
-keep class com.fasterxml.jackson.databind.ObjectWriter {
public ** writeValueAsString(**);
}
-keepnames class com.fasterxml.jackson.** { *; }
-dontwarn com.fasterxml.jackson.databind.**
当然,我仍然愿意接受有关如何使用 Gson 解决问题的建议,感谢任何建议
关于java - 当运行启用了 proguad 的版本变体时,Gson 映射到 pojo 会返回 null,即使添加了 @SerializedName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53034538/