使用 GSON 在自定义 class 中添加序列化方法

Add serialization method in custom class with GSON

我正在使用 Google Gson 将 Java 个对象序列化为 JSON。现在,我正在使用 registerTypeAdapter 方法为一些 classes 添加自定义序列化。 通过使用它,我需要将我想要序列化的所有 classes 导入到我的项目中。

由于我正在处理一个对象可以附加自定义 classes 的项目,因此我正在寻找一种创建特定方法的解决方案(例如,toJson)并告诉 Gson 在以默认模式序列化之前搜索该方法。

public class Banana {

    ...

    public JsonObject toJson() {
        // do stuff here
    }
}

当Gson发现这个方法存在时,就使用它,否则继续使用默认的序列化。

这是正确的方法吗?是否有替代方法将序列化代码包含到 class?

我相信你应该使用 TypeAdapterFactory

让您的 类 具有自定义序列化实现一些接口,例如:

interface CustomSerializable {
    JsonObject toJson();
}

然后实现类似的东西:

public class CustomTypeAdapterFactory implements TypeAdapterFactory {
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        // if given type implements CustomSerializable return your TypeAdapter 
        // that is designed to use above mentioned interface
        // so it uses method toJson() appropriately
       
        // else return null for default serialization   
        return null;
    }
}

那么就是注册自定义工厂一次,例如:

Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(new CustomTypeAdapterFactory())
    .create();

如果您不能更改 类 来实现 CustomSerializable,您也可以随时使用反射来确定 inf 有一个方法 toJson() 但是如果有这样的方法可能会产生严重的副作用而不是你添加的。