java Google 的 GSON 是否使用构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40441460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Google's GSON use constructors?
提问by Guido
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:
在处理我们的项目时,我想知道一些事情。Google 的 GSON API 是否使用了您要反序列化的 JSON 的构造函数?例如:
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?
我有一个 JSON 字符串,我想将其转换为 Employee 对象。Employee 对象有一个构造函数,它对参数进行一些检查(例如,它的 ID > 0)。我们使用下面的代码来反序列化 JSON。但是在将 JSON 反序列化为 Employee 时甚至调用了这个构造函数吗?
Link to GSON: https://github.com/google/gson
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);
}
回答by thatguy
Libraries like GSON, Hymanson 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、Hymanson 或 Java Persistence API (JPA) 等库通常使用无参数(默认)构造函数来实例化对象并通过反射设置其字段。在较新版本的 GSON 中,您甚至不必再声明默认构造函数,请参见此处。
If you have to call a specific constructor in GSON, you can implement a custom JsonDeserializer
, like already mentioned here.
如果您必须在 GSON 中调用特定的构造函数,您可以实现自定义JsonDeserializer
,就像这里已经提到的那样。
In other libraries like Hymanson, you can define the deserialization on methods, instead of fields (like GSON does), which allows you to substitute the missing specialized constructor call.
在像 Hymanson 这样的其他库中,您可以定义方法的反序列化,而不是字段(就像 GSON那样),这允许您替换缺少的专用构造函数调用。