22

I was wondering something when working on our project. Does the GSON API from Google use the constructors from the JSON's you want to deserialize? So for example:

I've got a JSON String which I want to convert to an Employee object. The Employee object has a constructor which applies some checks to the parameters (for example, is it's ID > 0). We're using the code below to deserialize the JSON's. But is this constructor even called when deserializing the JSON to Employee?

Link to GSON: https://github.com/google/gson

EDIT: So after experimenting with break points I figured out the constructor is not called. Does anybody know a way to get it called anyway?

/**
 * The GSON class to help you create and de-serialize the JSON objects.
 */
Gson gson = new Gson();

/**
 * Convert JSON to an object.
 * @param json The JSON to convert.
 * @param cls The class to convert to.
 * @return The converted JSON to object.
 */
public Object jsonToObject(String json, Class<?> cls) {
    return gson.fromJson(json, cls);
}
Guido
  • 1,161
  • 3
  • 12
  • 33
  • 2
    put a breakpoint in the constructor and debug the code, no? –  Nov 05 '16 at 18:05
  • 1
    @RC. Yes you're right, I just tested it and the constructor is not called. – Guido Nov 05 '16 at 18:11
  • 3
    I would assume it uses empty constructor to instantiate the object, and the read-in fields would be set using reflection directly. – EpicPandaForce Nov 05 '16 at 18:17
  • Yes I figured that out. @EpicPandaForce – Guido Nov 05 '16 at 18:20
  • 1
    As I stated in my answer, you need to implement a custom `JsonDeserializer` and call a constructor from there. GSON does not support calling constructors, yet. – thatguy Nov 08 '16 at 17:08

1 Answers1

26

Libraries like GSON, Jackson or the Java Persistence API (JPA) generally use a no-argument (default) construtor to instantiate an object and set its fields via reflection. In newer versions of GSON, you do not even have to declare a default constructor anymore, see here.

If you have to call a specific constructor in GSON, you can implement a custom JsonDeserializer, like already mentioned here.

In other libraries like Jackson, you can define the deserialization on methods, instead of fields (like GSON does), which allows you to substitute the missing specialized constructor call.

Community
  • 1
  • 1
thatguy
  • 21,059
  • 6
  • 30
  • 40
  • 4
    `Jackson` has an annotation `@JsonCreator` that now lets you mark constructors to be used for serialization. –  Jun 26 '18 at 15:50