I have a Java class that is a table data model in DynamoDB. I want to use DynamoDBMapper to save and load elements from Dynamo. One member of the class is List<MyObject> . So I used JsonMarshaller<List<MyObject>> to serialize and de-serialize this field.
The list can be serialized successfully by JsonMarshaller . However, when I try to restore the record and read the list, it throws an exception: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyObject . It seems that JsonMarshaller deserializing the data in LinkedHashMap instead of MyObject . How can I get rid of this problem?
MCVE:
// Model.java @DynamoDBTable(tableName = "...") public class Model { private String id; private List<MyObject> objects; public Model(String id, List<MyObject> objects) { this.id = id; this.objects = objects; } @DynamoDBHashKey(attributeName = "id") public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDBMarshalling(marshallerClass = ObjectListMarshaller.class) public List<MyObject> getObjects() { return this.objects; } public void setObjects(List<MyObject> objects) { this.objects = objects; } }
// MyObject.java public class MyObject { private String name; private String property; public MyObject() { } public MyObject(String name, String property) { this.name = name; this.property = property; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getProperty() { return this.property; } public void setProperty(String property) { this.property = property; } }
// ObjectListMarshaller.java public class ObjectListMarshaller extends JsonMarshaller<List<MyObject>> {}
// Test.java public class Test { private static DynamoDBMapper mapper; static { AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider() mapper = new DynamoDBMapper(client); } public static void main(String[] args) { MyObject obj1 = new MyObject("name1", "property1"); MyObject obj2 = new MyObject("name2", "property2"); List<MyObject> objs = Arrays.asList(obj1, obj2); Model model = new Model("id1", objs); mapper.save(model); // success Model retrieved = mapper.load(Model.class, "id1"); for (MyObject obj : retrieved.getObjects()) { // exception } } }
source share