我有一個Java類,它是DynamoDB中表的數據模型。我想使用Dynamo的DynamoDBMapper
至save
和load
項目。該班的一名成員是List<MyObject>
。所以我使用JsonMarshaller<List<MyObject>>
來序列化和反序列化這個字段。DynamoDB JsonMarshaller無法反序列化對象列表
該列表可以通過JsonMarshaller
成功序列化。但是,當我嘗試檢索條目並讀取列表時,它會引發異常:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyObject
。它看起來像JsonMarshaller
將數據反序列化到LinkedHashMap
而不是MyObject
。我怎樣才能擺脫這個問題?
的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
}
}
}
youryour marshaller怎麼沒有實現'DynamoDBMarshaller'?你能提供[MCVE](http://stackoverflow.com/help/mcve)來重現異常嗎? – mkobit
添加了MCVE。由於''JsonMarshaller''實現了''DynamoDBMarshaller'',所以你不需要再次實現它。 –