Let's say I have the following model class:
public class Product
{
private int ProductId;
private String Name;
public Product(){
setProductId(0);
setName("");
}
public void setProductId(int i){
if(i >= 0) {
ProductId = i;
} else {
ProductId = 0;
}
}
public int getProductId(){
return ProductId;
}
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 conversion 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 fields. Because of this, I get the following results from two Json-Strings:
Product 1: ProductId = 1; Name = "A Product";
Product 2: ProductId = 2; Name = "Another Product";
^ This is the result I want, so there is no problem.
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 to get Gson to use Setters instead?
I know how I can get Gson to use a constructor that has no parameters , but can I get Gson to use Setters? (Or, perhaps, a constructor with parameters, then I will just add another constructor, which received all the Model fields as parameters.)