'Gson RuntimeTypeAdapter - Cannot serialize class because it already defines a field name

I ran into an issue with serializing polymorphic objects so I'm trying to use RuntimeTypeAdapter to fix that.
Here's how my Gson instance is defined and how I'm using it:

RuntimeTypeAdapterFactory<Enemy> adapter = RuntimeTypeAdapterFactory.of(Enemy.class,"enemyType")
                .registerSubtype(Ranged.class, "Ranged")
                .registerSubtype(Melee.class, "Melee")
                .registerSubtype(Sniper.class, "Sniper")
                ;
        gson = new GsonBuilder().registerTypeAdapterFactory(adapter).create();
...
public GameStateData loadGameState(String path) throws FileNotFoundException {
        FileReader fileReader = new FileReader(path);
        gameStateData = gson.fromJson(fileReader, GameStateData.class);
        try {
            fileReader.close();
        } catch (IOException e) {
            System.err.println("Error closing save file");
        }
        return gameStateData;
    }

public void writeGameState(String path) throws IOException {
        FileWriter fileWriter = new FileWriter(path);
        gson.toJson(gameStateData, fileWriter);
        fileWriter.close();
    }

Both type and enemyType are already existing fields within Enemy, when trying to use either or without the adapter's typeFieldName specified leads to the following error when trying to serialize:

com.google.gson.JsonParseException: cannot serialize enemies.Ranged because it already defines a field named enemyType

I also tried setting an unused value for typeFieldName but that lead to the issue that my Ranged type entity was saved as an Enemy. Both type and enemyType are enums, although different ones. What type should typeFieldName be?

Edit: Ended up solving this issue by re-filling the ArrayList with new Objects with their specific constructors based on enemyType. Looking at my code my thoroughly my error seemed to have been using a different (and differently configured) Gson instance for deserializing.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source