Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to deserialise EnumSet from String

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.

like image 792
Andremoniy Avatar asked Mar 28 '13 15:03

Andremoniy


People also ask

How does Jackson deserialize enum?

Deserializing JSON String to Enum Using @JsonValue Annotation. The @JsonValue annotation is one of the annotations which we can use for both serializing and deserializing enums. Enum values are constants, and due to this, @JsonValue annotation can be used for both. First we simply add the getter method to our Distance.

How do I pass enum as JSON?

All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .

Can we serialize enums?

To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.

Can you convert string to enum?

IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.


1 Answers

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()))
like image 164
anho-dev Avatar answered Sep 23 '22 10:09

anho-dev