The Gson User Guide states that we must define a default constructor of no-args for any class that will work with Gson correctly. Moreover, javadoc in the Gson InstanceCreator class says that an exception will be thrown if we try to deserialize an instance of a class that does not have a default constructor, and we should use InstanceCreator in such cases. However, I tried to test the use of Gson with a class that does not have a default constructor, and both serialization and deserialization work without problems.
Here is the code snippet for deserializaiton. A class without a constructor without arguments:
public class Mushroom { private String name; private double diameter; public Mushroom(String name, double diameter) { this.name = name; this.diameter = diameter; }
and test:
@Test public void deserializeMushroom() { assertEquals( new Mushroom("Fly agaric", 4.0), new Gson().fromJson( "{name:\"Fly agaric\", diameter:4.0}", Mushroom.class)); }
which works great.
So my question is: Can I use Gson without having to have a default constructor, or are there some circumstances where it will not work?
java json gson default-constructor
raindev Sep 05 '13 at 20:11 2013-09-05 20:11
source share