【发布时间】:2014-09-26 20:19:46
【问题描述】:
假设我有以下模型类:
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-Strings 的以下结果:
// 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 使用 Setter?
I know how I can force Gson to use a Constructor that doesn't has any parameters,但我也可以强制 Gson 使用 Setters 吗? (或者也许是一个带参数的构造函数,然后我将添加另一个构造函数,它将所有模型的字段作为参数。)
【问题讨论】:
标签: java android json gson converter