Search code examples
javagson

How to write custom serializer for proxy classes


I need to serialize/deserialize a POJO with enum. I have the following 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);
}

How can I write a custom serializer/deserializer for proxy classes using Gson library? I can't use another library.


Solution

  • I've been found the solution. Need to change

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

    to

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

    and all work fine.