Let's say I have the following Model-class:
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;
}
}
The following Json-Strings:
"[{\"$id\":\"1\",\"ProductId\":1,\"Name\":\"A Product\"}," +
"{\"$id\":\"2\",\"ProductId\":2,\"Name\":\"Another Product\"}]";
And
"[{\"$id\":\"1\",\"ProductId\":1,\"Name\":\"A Product\"}," +
"{\"$id\":\"2\",\"ProductId\":-4,\"Name\":null}]";
And the following convertion method:
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);
}
By default Gson uses the fields. Because of that I get the following results of the two Json-Strings:
// Json-String 1:
Product 1: ProductId = 1; Name = "A Product";
Product 2: ProductId = 2; Name = "Another Product";
^ This is the result I want, so no problem here.
// Json-String 2:
Product 1: ProductId = 1; Name = "A Product";
Product 2: ProductId = -4; Name = null;
^ This is not the result I want, because for the second Product I want this instead:
Product 2: ProductId = 0; Name = "";
How can I force Gson to use the Setters instead?
I know how I can force Gson to use a Constructor that doesn't has any parameters, but can I also force Gson to use Setters? (Or perhaps a Constructor with parameters, then I'll just add another Constructor that got all Model's fields as parameters.)