Try using enableComplexMapKeySerialization
if you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization.
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.setPrettyPrinting().create();
Relevant post
From the documentation of enableComplexMapKeySerialization
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 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 Point class, which contains an x and y coordinate, to/from the JSON Primitive string value "(x,y)". The Java map would then be serialized as a JsonObject
.
Below is an example:
Gson gson = new GsonBuilder()
.register(Point.class, new MyPointTypeAdapter())
.enableComplexMapKeySerialization()
.create();
Map<Point, String> original = new LinkedHashMap<Point, String>();
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:
{
"(5,6)": "a",
"(8,8)": "b"
}
By default Gson converts application classes to JSON using its built-in type adapters. If Gson's default JSON conversion isn't appropriate for a type, extend this class to customize the conversion. Here's an example of a type adapter for an (X,Y) coordinate point:
public class PointAdapter extends TypeAdapter<Point> {
public Point read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String xy = reader.nextString();
String[] parts = xy.split(",");
int x = Integer.parseInt(parts[0]);
int y = Integer.parseInt(parts[1]);
return new Point(x, y);
}
public void write(JsonWriter writer, Point value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
String xy = value.getX() + "," + value.getY();
writer.value(xy);
}
}
Read more about GSON TypeAdapter