Felipe Micaroni Lalli Felipe Micaroni Lalli - 1 month ago 15
Java Question

Is it mandatory to keep a default constructor on classes handled by Gson?

If I create a custom constructor, need I create one with no arguments to use with Gson?

Answer

Option 1: Yes, unless you create your own JsonDeserializer and JsonSerializer, in which case, your serializers can use whatever constructor you want.

Specifically, I would advise you to do the extra bit of work if you have other requirements in your classes, such as them being immutable, or if you want to guarantee a minimum state after initialization.

PS: actually, I supose the JsonDeserializer is enough. Insights anyone?

Option 2: (see Eugen's answer) consider using Genson instead

Option 3: (see Robertiano's answer) keep the default deserializers and implement InstanceCreator instead