Search code examples
javahashmapgson

How to serialize HashMap<Object,Object> with GSON?


I am trying to serialize HashMap which has custom objects (both of the same type) both as a key and a value. However gson is outputing something like this:

{ key.toString():{value}}

Basicaly instead of serializing the object used as key in the map it just uses its toString value. The value object gets serialized fine. Resulting Json obviously cannot be deserialized. How do I convince GSON to fully serialize the key object?

EDIT: The objects that are stored in HashMap contains information about players (I am building custom matchmaker for our board game group). They look like this:

public class Player implements Serializable{
private static final long serialVersionUID = 42L;
private String playerName,faction,teamName;
private HashMap<String,Integer> resources;

The hashmap is supposed to contain informations about upcoming matches, basicaly key playing against value like this:

HashMap<Player,Player> matchMap=new HashMap<>();
matchMap.put(player1,opponentForPlayer1);

Solution

  • Based on fluffys comment the simplest solution is using enableComplexMapKeySerialization() while creating gson object like this:

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

    If that is not available or working for whatever reason pcsutars answer also work.