0

I have a class like this:

@JsonInclude(Include.NON_NULL)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class VPC
{
    @NotNull()
    private String id;

    @NotNull()
    @DynamoDBMarshalling(marshallerClass = SubnetTypeMarshaller.class)
    private Map<SubnetType, List<String>> subnetTypeToId;
}

Here, SubnetType is a enum like this:

public enum SubnetType
{

    AppSubnet,

    DBSubnet,

    DMZSubnet;
}

Now, I want to store the above in AWS DynamoDB. For this, I need to convert enum to a string and I have written the following.

public class SubnetTypeMarshaller implements DynamoDBMarshaller<Map<SubnetType, List<String>>>
{

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

    @Override
    public String marshall(final Map<SubnetType, List<String>> securityGroupTypeListMap)
    {
        return gson.toJson(securityGroupTypeListMap);
    }

    @Override
    public Map<SubnetType, List<String>> unmarshall(final Class<Map<SubnetType, List<String>>> aClass,
            final String s)
    {
        return gson.fromJson(s, aClass);
    }
}

But this doesn't work. While getting values from DB, I get the following error:

java.lang.String cannot be cast to java.lang.Enum (through reference chain: java.util.ArrayList[0]->["security_group_type_to_id"])

Am I missing something in this? I searched on other posts how to convert enums to string using @SerializedName annotation. But that didn't work either. I have also tried the solution mentioned in the other post, but it doesn't work. Maybe because my enum is in itself a part of map and I can't really annotate the enum attribute inside the map.

sarah
  • 247
  • 1
  • 9
  • 19
  • Possible duplicate of [serialize and deserialize enum with Gson](https://stackoverflow.com/questions/16740078/serialize-and-deserialize-enum-with-gson) – Tschallacka Jul 25 '17 at 12:30
  • @Tschallacka, my question is different. I have already what's mentioned in the other post. – sarah Jul 25 '17 at 14:49

1 Answers1

0

Gson provides default serialization for enums, if you want to change it you have to build your own adapter.

Check gson docs for registerTypeAdapter.

Aldeguer
  • 821
  • 9
  • 32