Java Does Google GSON use constructors?

I was interested in something while working on our project. Is Google's GSON API using the JSON constructors you want to deserialize? For example:

I have a JSON string that I want to convert to an Employee object. The Employee object has a constructor that applies some checks to parameters (for example, this identifier> 0). We use the following code to deserialize JSON. But is this constructor even called when deserializing JSON for Employee?

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

EDIT: So after experimenting with breakpoints, I realized that the constructor is not called. Does anyone know a way to get it 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); } 
+6
source share
1 answer

Libraries such as GSON, Jackson, or the Java Persistence API (JPA) usually use the no-argument (default) constructor to create an object and set its fields through reflection. In newer versions of GSON, you no longer need to declare a default constructor, see here .

If you need to call a specific constructor in GSON, you can implement a custom JsonDeserializer , as mentioned here .

In other libraries, such as Jackson, you can define deserialization of methods rather than fields (for example, GSON does ), which allows you to replace the missing constructor call.

+7
source

Source: https://habr.com/ru/post/1012062/


All Articles