Enabling this feature will only change the serialized form if the map key is a complex type (i.e. non-primitive) in its
serialized JSON form. The default implementation of map serialization uses {@code toString()}on the key; however, when this is called then one of the following cases apply:
Maps as JSON objects
For this case, assume that a type adapter is registered to serialize and deserialize some {@code Point} class, which contains an x and y coordinate,to/from the JSON Primitive string value {@code "(x,y)"}. The Java map would then be serialized as a {@link JsonObject}.
Below is an example:
{@code Gson gson = new GsonBuilder() .register(Point.class, new MyPointTypeAdapter()) .enableComplexMapKeySerialization() .create(); Map original = new LinkedHashMap(); original.put(new Point(5, 6), "a"); original.put(new Point(8, 8), "b"); System.out.println(gson.toJson(original, type));}
The above code prints this JSON object:
{@code}{ "(5,6)": "a", "(8,8)": "b" } }
Maps as JSON arrays
For this case, assume that a type adapter was NOT registered for some {@code Point} class, but rather the default Gson serialization is applied.In this case, some {@code new Point(2,3)} would serialize as {@code}{"x":2,"y":5}}.
Given the assumption above, a {@code Map} will beserialize as an array of arrays (can be viewed as an entry set of pairs). Below is an example of serializing complex types as JSON arrays:
{@code Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .create(); Map original = new LinkedHashMap(); original.put(new Point(5, 6), "a"); original.put(new Point(8, 8), "b"); System.out.println(gson.toJson(original, type));}The JSON output would look as follows: {@code [ [}{ "x": 5, "y": 6 }, "a" ], [ { "x": 8, "y": 8 }, "b" ] ] }
@return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
@since 1.7