简体   繁体   中英

Serializing a map of enums with Gson with custom serialization

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} ?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM