Serializing a map of enums with Gson with custom serialization

前端 未结 1 375
野趣味
野趣味 2021-01-12 17:16

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 foll

相关标签:
1条回答
  • 2021-01-12 17:43

    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();
    
    0 讨论(0)
提交回复
热议问题