I was writing a program to return JSON object using gson and I discovered something peculiar. Basically when I wanted to convert following object to JSON it gave me null.
Customer customer = new Customer() {
{
setId(1);
setName("Foo bar");
setAddress("Some Address");
}
};
System.out.println(gson.toJson(customer));
where Customer looks like this
public class Customer{
int id;
String name;
String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
but when I created object properly like
Customer customer = new Customer();
customer.setId(1);
customer.setName("Foo bar");
customer.setAddress("Some Address");
System.out.println(gson.toJson(customer));
it worked perfectly fine and gave output as supposed to. Why does it matter how I create my objects. Is there difference between two methods?