7

I'd like to serialise some EnumSet<FooType> to String using its toString() method.

E.g.: EnumSet.of(FooType.COMMON, FooType.MEDIUM).toString() will give [COMMON, MEDIUM].

The question is about an elegant way to deserialise such a string back to the EnumSet<FooSet>. I'm looking for some commonly known library (may be like apache-commons) or a standard Util-class for such things.

Something like: EnumSetUtil.valueOf(FooType.class, "[COMMON, MEDIUM]")

I've implemented this thing in such way:

public static <E extends Enum<E>> EnumSet<E> valueOf(Class<E> eClass, String str) {
    String[] arr = str.substring(1, str.length() - 1).split(",");
    EnumSet<E> set = EnumSet.noneOf(eClass);
    for (String e : arr) set.add(E.valueOf(eClass, e.trim()));
    return set;
}

But, may be there is a ready solution, or a dramatically easy way for doing this.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • I know of no such library, and your method looks pretty good. I would probably use a regex (_personal preference_) instead, and call the method `fromString` to imply its inverse relationship to `toString` (though the java convention would likely be something like `parseEnumSet`), but I don't find any flaw in what you are doing. – Lucas Mar 28 '13 at 15:25
  • Serializing and deserializing "by hand" is often faster and easier to debug for simple structures but you usually hit pretty fast the corner cases: for example what happens if one your enums contains a comma `,` ? Then you will need to start escaping commas and complicate your regex, etc.. – Bruno Grieder Mar 28 '13 at 16:14

3 Answers3

7

With Java 8 you can do something like this with Lambda expressions and streams:

EnumSet.copyOf(Arrays.asList(str.split(","))
.stream().map(FooType::valueOf).collect(Collectors.toList()))
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
anho-dev
  • 1,871
  • 1
  • 14
  • 5
0

With guava 19.0:

    Iterable<String> i = Splitter.on(",")
        .trimResults(CharMatcher.WHITESPACE.or(CharMatcher.anyOf("[]")))
        .split(str);
    Set<YourEnum> result = FluentIterable.from(i)
        .transform(Enums.stringConverter(YourEnum.class)).toSet();

OR another way with JSON library if you can accept String format like this ['COMMON', 'MEDIUM'].

Anderson
  • 2,496
  • 1
  • 27
  • 41
0

Using Gson ('com.google.code.gson:gson:2.3.1') library you can do:

public static EnumSet getEnumObject(Type type, String jsonStrToDeserialize) {
    Gson gson = new Gson();
    return jsonStrToDeserialize == null ? null : (EnumSet) gson.fromJson(jsonStrToDeserialize, type);
}
user465363
  • 531
  • 5
  • 10