Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Google's GSON use constructors?

Tags:

java

json

gson

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);
}
like image 454
Guido Avatar asked Nov 05 '16 17:11

Guido


People also ask

Does Gson use constructor?

Gson requires the class to have a default no-args constructor.

How does Gson serialize?

Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.

Is Gson better than Jackson?

Conclusion Both Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.


1 Answers

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.

like image 189
thatguy Avatar answered Oct 05 '22 10:10

thatguy