假设我有以下模型类:
public class Product
{
private int ProductId;
private String Name;
public Product(){
setProductId(0);
setName("");
}
// Getter and Setter for the Product-ID
public void setProductId(int i){
if(i >= 0) {
ProductId = i;
} else {
ProductId = 0;
}
}
public int getProductId(){
return ProductId;
}
// Getter and Setter for the Name
public void setName(String n){
if(n != null && n.length() > 0) {
name = n;
} else {
name = "";
}
}
public String getName(){
return name;
}
}
以下 Json 字符串:
"[{\"$id\":\"1\",\"ProductId\":1,\"Name\":\"A Product\"}," +
"{\"$id\":\"2\",\"ProductId\":2,\"Name\":\"Another Product\"}]";
和
"[{\"$id\":\"1\",\"ProductId\":1,\"Name\":\"A Product\"}," +
"{\"$id\":\"2\",\"ProductId\":-4,\"Name\":null}]";
还有下面的转换方法:
public void jsonToProducts(String json){
ArrayList<Product> p = null;
if(json != null && json.length() > 0){
try{
Type listType = new TypeToken<ArrayList<Product>>(){}.getType();
p = new Gson().fromJson(json, listType);
}
catch(JsonParseException ex){
ex.printStackTrace();
}
}
setProducts(p);
}
默认情况下 Gson 使用字段。因此,我得到了两个 Json 字符串的以下结果:
// Json-String 1:
Product 1: ProductId = 1; Name = "A Product";
Product 2: ProductId = 2; Name = "Another Product";
^ 这就是我想要的结果,所以这里没问题。
// Json-String 2:
Product 1: ProductId = 1; Name = "A Product";
Product 2: ProductId = -4; Name = null;
^ 这不是我想要的结果,因为对于第二个产品我想要的是:
Product 2: ProductId = 0; Name = "";
我如何强制 Gson 使用 Setters?
I know how I can force Gson to use a Constructor that doesn't has any parameters ,但我也可以强制 Gson 使用 Setters 吗? (或者也许是一个带参数的构造函数,然后我将添加另一个构造函数,它将模型的所有字段作为参数。)
最佳答案
我看过Gson's User Guide看起来它还没有实现。支持 Getters 和 Setters 放在 their TODO/issues-list 上(issue 232)。
我有一个临时的(低效且丑陋的解决方案):
public void jsonToProducts(String json){
ArrayList<Product> products = null;
if(json != null && json.length() > 0){
try{
Type listType = new TypeToken<ArrayList<Product>>(){}.getType();
products = new Gson().fromJson(json, listType);
}
catch(JsonParseException ex){
ex.printStackTrace();
}
}
// TODO: Replace when Gson supports Setters or Parameterized Constructors
if(products != null && products.size() > 0){
for(Product p : products){
p.setProductId(p.getProductId());
p.setName(p.getName());
}
}
setProducts(products);
}
我暂时接受这个作为答案。如果有人知道处理 Gson 缺乏 Setter 支持的更好方法,我将不胜感激。 (特别是因为我的产品列表大约有 1250 个产品,所以循环遍历它并重置所有字段对于移动应用程序的性能来说并不是那么好。幸运的是,这只在启动时发生一次..)
关于java - 强制 GSON 一般使用包含 Setter 或 Setter 的构造函数,而不是 Fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25117329/