Following suggestions in Using Enums while parsing JSON with GSON, I am trying to serialize a map whose keys are an enum
using Gson.
Consider the following class:
public class Main {
public enum Enum { @SerializedName("bar") foo }
private static Gson gson = new Gson();
private static void printSerialized(Object o) {
System.out.println(gson.toJson(o));
}
public static void main(String[] args) {
printSerialized(Enum.foo); // prints "bar"
List<Enum> list = Arrays.asList(Enum.foo);
printSerialized(list); // prints ["bar"]
Map<Enum, Boolean> map = new HashMap<>();
map.put(Enum.foo, true);
printSerialized(map); // prints {"foo":true}
}
}
Two questions:
printSerialized(map)
print {"foo":true}
instead of {"bar":true}
?{"bar":true}
?Gson can serialize and deserialize enums using the @SerializedName annotation. If we annotate an enum with the @SerializedName we can supply a value which will be mapped when GSON serializes or deserializes the JSON to or from Java Object.
Because enums are automatically Serializable (see Javadoc API documentation for Enum), there is no need to explicitly add the "implements Serializable" clause following the enum declaration. Once this is removed, the import statement for the java. io.
Gson can serialize a collection of arbitrary objects but can't deserialize the data without additional information. That's because there's no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type.
Both Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.
Gson uses a dedicated serializer for Map
keys. This, by default, use the toString()
of the object that's about to be used as a key. For enum
types, that's basically the name of the enum
constant. @SerializedName
, by default for enum
types, will only be used when serialized the enum
as a JSON value (other than a pair name).
Use GsonBuilder#enableComplexMapKeySerialization
to build your Gson
instance.
private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
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