gson 如何为代理类编写自定义序列化程序

vddsk6oq  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(194)

我需要序列化/反序列化一个带有枚举的POJO。我有以下DTO:

public enum MyEnum {
    VAL1("val1"),
    VAL2("val2") {
         @Override
         public String getValue() {
             return "test2";
         }
    };
    private final String name;
    MyEnum(String name) {
       this.name = name;
    }

    public String getValue() {
       return name;
    }

}
public class MyPojo {
    public MyEnum prop;
}
public static void main(String... args) {
    Gson gson = new GsonBuilder().registerTypeAdapter(MyEnum.class, new MyEnumSeserializer());
    MyPojo p = new MyPojo();
    p.prop = MyEnum.VAL2;   // and I get MyEnum$1.class and My serializer doesn't work
    String json = gson.toJson(p);
    MyPojo p1 = gson.fromJson(json, MyPojo.class);
}

如何使用Gson库为代理类编写自定义序列化程序/反序列化程序?我不能使用其他库。

oxiaedzo

oxiaedzo1#

我已经找到了解决办法。需要改变

new GsonBuilder().registerTypeAdapter(MyEnum.class, new MyEnumSeserializer());

new GsonBuilder(). registerTypeHierarchyAdapter(MyEnum.class, new MyEnumSeserializer());

且都工作正常。

相关问题