Gson user guide states that we should define default no-args constructor for any class to work with Gson properly. Even more, in the javadoc on Gson's InstanceCreator class said that exception will be thrown if we try to deserialize instance of class missing default constructor and we should use InstanceCreator in such cases. However, I've tried to test use Gson with class lacking default constructor and both serialization and deserialization work without any trouble.

Here is the piece of code for deserializaiton. A class without non-args constructor:

public class Mushroom {
    private String name;
    private double diameter;

    public Mushroom(String name, double diameter) {
        this.name = name;
        this.diameter = diameter;
    }

    //equals(), hashCode(), etc.
}

and a test:

@Test
public void deserializeMushroom() {
    assertEquals(
            new Mushroom("Fly agaric", 4.0),
            new Gson().fromJson(
                    "{name:\"Fly agaric\", diameter:4.0}", Mushroom.class));
}

这很好用.

所以我的问题是:could I actually use Gson without need to have default constructor or there is any circumstances when it will not work?

推荐答案

As of Gson 2.3.1.

Regardless of what the Gson documentation says, if your class doesn't have an no-args constructor and you have not registered any InstanceCreater objects, then it will create an ObjectConstructor (which constructs your Object) with an UnsafeAllocator which uses Reflection to get the allocateInstance method of the class sun.misc.Unsafe to create your class' instance.

Unsafe class个围绕着无参数构造函数的缺乏,有many other dangerous uses个.allocateInstance个州

分配一个实例,但不要运行任何构造函数.初始化

So it doesn't actually need a constructor and will go around your two argument constructor. See some examples here.

If you do have a no-args constructor, Gson will use an ObjectConstructor which uses that default Constructor by calling

yourClassType.getDeclaredConstructor(); // ie. empty, no-args

My 2 cents: Follow what Gson says and create your classes with a no-arg constructor or register an InstanceCreator. You might find yourself in a bad position using Unsafe.

Json相关问答推荐

如何在VegaLite中应用Times New Roman,CaliBiri字体

(Kotlin)com.google.gson.internal.LinkedTreeMap无法转换为com.example.phonetest2.model.HallData

如何避免解析 ISuperObject 类型字段中的 json 对象

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

使用 jq 将非统一的 json 输出转换为汇总表

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

如何使用 SQL Server 将 json 存储为字符串的列分解/规范化为行和列?

颠簸转换问题

流编写器未写入 webapi 中的 JSON 文件

如何让 JSON.NET 忽略对象关系?

现代浏览器一次可以处理多少个 HTML 元素?

如何在不解析的情况下在javascript中同步包含JSON数据?

Retrofit 2.0 如何解析嵌套的 JSON 对象?

在 JSON 字符串中react i18n 换行符

使用 JSON 的 javascript 深拷贝

验证和格式化 JSON 文件

如何在java中比较来自JsonObject的空值

在android中使用GSON解析带有动态key和value的JSON

如何使用 Javascript 将数据写入 JSON 文件

如何在 JAVA 中对 JSONArray 进行排序