By default, no-args constructor is required for Gson?

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; } //equals(), hashCode(), etc. } 

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?

+42
java json gson default-constructor
Sep 05 '13 at 20:11
source share
2 answers

As with Gson 2.3.1.

Regardless of what Gson documentation says, if your class does not have a no-args constructor and you have not registered any InstanceCreater objects, then it will create an ObjectConstructor (which builds your object) using UnsafeAllocator , which uses Reflection to get the allocateInstance method of sun.misc.Unsafe class sun.misc.Unsafe to instantiate your class.

This Unsafe class bypasses the lack of a no-args constructor and has many other dangerous uses . allocateInstance state

Select the instance, but do not run any constructor. Initializes the class, if it has not already been.

Thus, in fact, it does not need a constructor and will bypass your two argument constructors. See examples here .

If you have a no-args constructor, Gson will use an ObjectConstructor , which uses this default Constructor , calling

 yourClassType.getDeclaredConstructor(); // ie. empty, no-args 

My 2 cents: Follow the directions of Gson and create your classes using the no-arg constructor or register an InstanceCreator . You may be in a bad position using Unsafe .

+67
Sep 05 '13 at 20:29
source share

Jackson has a good solution:

stack overflow

The point is to tell the serializer using the Mix-Ins function which JSON fields to use when using the constructor with arguments.

If this object is part of an external library, you can "remotely annotate" using the Creator function.

+1
Mar 20 '15 at 15:27
source share



All Articles