Gson: Is there an easier way to serialize a map

前端 未结 5 2156
野趣味
野趣味 2020-11-28 04:36

This link from the Gson project seems to indicate that I would have to do something like the following for serializing a typed Map to JSON:

    public static         


        
5条回答
  •  天命终不由人
    2020-11-28 05:31

    Default

    The default Gson implementation of Map serialization uses toString() on the key:

    Gson gson = new GsonBuilder()
            .setPrettyPrinting().create();
    Map original = new HashMap<>();
    original.put(new Point(1, 2), "a");
    original.put(new Point(3, 4), "b");
    System.out.println(gson.toJson(original));
    

    Will give:

    {
      "java.awt.Point[x\u003d1,y\u003d2]": "a",
      "java.awt.Point[x\u003d3,y\u003d4]": "b"
    }
    


    Using enableComplexMapKeySerialization

    If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:

    Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
            .setPrettyPrinting().create();
    Map original = new HashMap<>();
    original.put(new Point(1, 2), "a");
    original.put(new Point(3, 4), "b");
    System.out.println(gson.toJson(original));
    

    Will return:

    [
      [
        {
          "x": 1,
          "y": 2
        },
        "a"
      ],
      [
        {
          "x": 3,
          "y": 4
        },
        "b"
      ]
    ]
    

    More details can be found here.

提交回复
热议问题