0

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?

Kshitij Dhakal
  • 816
  • 12
  • 24
  • 1
    Of course there's a difference. Make `Customer` final and your first approach won't work. Why? Because you're creating an anonymous instance of a subclass to `Customer`. That approach is called [double brace initialization](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) and has its drawbacks as Amongalen's link is highlighting. It you _really_ want to use code like this it might be better to create a builder and do something like `Customer customer = new CustomerBuilder().id(1).name("Foo bar").address("Some Address").build()`. – Thomas Sep 10 '19 at 12:08
  • 1
    The difference is that the first one creates an anonymous class and then object of that class. In the second case you create an object of `Customer` class. – Amongalen Sep 10 '19 at 12:08
  • 3
    Btw. read this: [Don’t be “Clever”: The Double Curly Braces Anti Pattern](https://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/) – Amongalen Sep 10 '19 at 12:09

1 Answers1

2

The reason the first case it is returning null because 'customer' object's class is an anonymous one which clazz.isAnonymousClass() return true

See below for GSon implementation

enter image description here

Nghia Do
  • 2,588
  • 2
  • 17
  • 31