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.
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.
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 .
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.
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.
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With