Jijokoickal / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Custom enum serializer does not work for enum with methods #547

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
Here is the code to reproduce the problem:
public class App {
    enum MyEnum {
        A {
            @Override
            String toJson() {
                return "a";
            }
        };

        abstract String toJson();
    }

    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(MyEnum.class, new MyEnumSerializer())
                .create();
        System.out.println(gson.toJson(MyEnum.A)); // Expected "a", but got "A"
    }

    static class MyEnumSerializer implements JsonSerializer<MyEnum> {
        @Override
        public JsonElement serialize(MyEnum src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.toJson());
        }
    }
}

What is the expected output? What do you see instead?
Expected "a", but got "A"

What version of the product are you using? On what operating system?
gson 2.2.4
jdk1.6.0_45_x64
win7 x64

Please provide any additional information below.
MyEnumSerializer will be used if it is registered for every concrete Enum value:
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(MyEnum.A.getClass(), new MyEnumSerializer())
                .create();

Original issue reported on code.google.com by vsorokin87@gmail.com on 11 Dec 2013 at 11:15

GoogleCodeExporter commented 9 years ago
You'd need to `registerTypeHierarchyAdapter` instead. Any enum member declaring 
some methods is a different subclass and `registerTypeAdapter` seems to require 
an exact match. To me it looks like a consistent behavior.

Original comment by Maaarti...@gmail.com on 13 Dec 2013 at 8:06

GoogleCodeExporter commented 9 years ago
I think you are right, `registerTypeHierarchyAdapter` works as expected.
This issue can be closed.

Original comment by vsorokin87@gmail.com on 16 Dec 2013 at 6:53

GoogleCodeExporter commented 9 years ago

Original comment by j...@squareup.com on 9 Aug 2014 at 6:01