Failure to deserialize an EnumSet

599 views
Skip to first unread message

Maurice Balick

unread,
Mar 15, 2013, 8:34:04 PM3/15/13
to googl...@googlegroups.com
I can't figure out how to serialize/deserialize an EnumSet. I thought that using TypeToken during deserialization would do the trick, but apparently not.

Here is a trivial example of what I am doing that fails:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.EnumSet;

public class Test2 {

    enum Color { red, blue, green, yellow, thistle }

    public static void main(String[] args) throws Exception {
        Gson gson = new Gson();
        EnumSet<Color> foo = EnumSet.of(Color.blue, Color.red);
        String json = gson.toJson(foo);
        EnumSet<Color> bar = (EnumSet<Color>)gson.fromJson(json, new TypeToken<EnumSet<Color>>() {}.getType());
        System.out.printf("foo: " + foo + "\nbar: " + bar + '\n');
    }
}

When I run this code, it fails with this error:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashSet cannot be cast to java.util.EnumSet
at com.nf.tests.exp.Test2.main(Test2.java:line in red)

I do not understand why gson.fromJson(...) returns a java.util.LinkedHashSet when it is asked for an EnumSet.

As always, any hint of what I am doing wrong would be much appreciated.

--Maurice

Inderjeet Singh

unread,
Mar 27, 2013, 10:23:53 AM3/27/13
to googl...@googlegroups.com
Seems like a bug in Gson. I added it at: http://code.google.com/p/google-gson/issues/detail?id=509

We will try to fix it in the next release.
Inder
coauthor, Gson

Inderjeet Singh

unread,
Apr 4, 2013, 5:18:59 PM4/4/13
to googl...@googlegroups.com
This bug has now been fixed in https://code.google.com/p/google-gson/source/detail?r=1228 and should make it to Gson 2.2.3

naseem regragui

unread,
Apr 12, 2013, 10:46:40 AM4/12/13
to googl...@googlegroups.com
It just so happens I have run into this problem today. Do you have a target release date for 2.2.3?

Thanks,

Naseem

Inderjeet Singh

unread,
Apr 12, 2013, 2:29:02 PM4/12/13
to googl...@googlegroups.com
Plan is to release it today! 
Reply all
Reply to author
Forward
0 new messages