Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a map of enums with Gson with custom serialization

Tags:

java

enums

gson

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:

  1. Why does printSerialized(map) print {"foo":true} instead of {"bar":true}?
  2. How can I get it to print {"bar":true}?
like image 778
mbroshi Avatar asked Aug 21 '15 20:08

mbroshi


People also ask

How do you serialize and deserialize enums with GSON?

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.

Can we serialize enums?

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.

What is GSON serialization and Deserialization?

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.

What is the difference between GSON and Jackson?

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.


1 Answers

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();
like image 115
Sotirios Delimanolis Avatar answered Sep 29 '22 08:09

Sotirios Delimanolis