簡體   English   中英

使用Gson使用自定義序列化序列化枚舉映射

[英]Serializing a map of enums with Gson with custom serialization

按照使用GSON解析JSON時使用枚舉的建議,我嘗試使用Gson序列化其鍵是enum的映射。

考慮以下課程:

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

兩個問題:

  1. 為什么printSerialized(map) print {"foo":true}而不是{"bar":true}
  2. 如何打印{"bar":true}

Gson為Map鍵使用專用的序列化器。 默認情況下,這使用將要用作鍵的對象的toString() 對於enum類型,它基本上是enum常量的名稱。 默認情況下,對於enum類型, @SerializedName僅在將enum序列化為JSON值(除了對名稱)時使用。

使用GsonBuilder#enableComplexMapKeySerialization來構建您的Gson實例。

private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM