By default, Gson serializes java.util.Map as a JSON object.
Key behaviors:
- Key Conversion: Since JSON keys must be strings, Gson calls
toString() on Map keys. null keys are converted to the string "null". - Deserialization: Requires a
TypeToken to specify the types of keys and values. - Complex Map Keys: To use complex objects as keys without relying on
toString(), use GsonBuilder.enableComplexMapKeySerialization(). This will serialize the Map as a JSON array of key-value pairs if any key is a complex type (array or object).
// Standard Map Serialization
Gson gson = new Gson();
Map<String, String> stringMap = new LinkedHashMap<>();
stringMap.put("key", "value");
stringMap.put(null, "null-entry");
String json = gson.toJson(stringMap); // ==> {"key":"value","null":"null-entry"}
// Complex Map Key Serialization
Gson gsonComplex = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<PersonName, Integer> complexMap = new LinkedHashMap<>();
// ... put items ...
String jsonComplex = gsonComplex.toJson(complexMap);
// ==> [[{"firstName":"John","lastName":"Doe"},30], ...]