Google的GSON是否使用构造函数

Google的GSON是否使用构造函数

本文介绍了Google的GSON是否使用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理我们的项目时,我想知道一些事情. Google的GSON API是否使用您要反序列化的JSON的构造函数?例如:

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:

我有一个JSON字符串,我想将其转换为Employee对象. Employee对象具有一个构造函数,该构造函数对参数进行了一些检查(例如,其ID> 0).我们正在使用下面的代码反序列化JSON.但是,当将JSON反序列化为Employee时,甚至会调用此构造函数吗?

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?

链接到GSON: https://github.com/google/gson

因此,在尝试了断点之后,我发现未调用构造函数.有人知道反正得到它的方法吗?

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);
}

推荐答案

像GSON,Jackson或Java Persistence API(JPA)之类的库通常使用无参数(默认)构造函数来实例化对象并通过反射设置其字段.在更新版本的GSON中,您甚至不必声明默认构造函数,请参见.

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.

如果必须在GSON中调用特定的构造函数,则可以实现自定义的JsonDeserializer,就像已经提到的.

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

在其他类似Jackson的库中,您可以在方法而不是字段上定义反序列化(例如GSON ),它使您可以替换缺少的专用构造函数调用.

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.

这篇关于Google的GSON是否使用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:28