我通过创建 MyCustomMarshaller 跟随here。
MyCustomMarshaller
public class MyCustomMarshaller implements DynamoDBMarshaller<List<DemoClass>> {
private static final ObjectMapper mapper = new ObjectMapper();
private static final ObjectWriter writer = mapper.writer();
@Override
public String marshall(List<DemoClass> obj) {
try {
return writer.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw failure(e,
"Unable to marshall the instance of " + obj.getClass()
+ "into a string");
}
}
@Override
public List<DemoClass> unmarshall(Class<List<DemoClass>> clazz, String json) {
final CollectionType
type =
mapper.getTypeFactory().constructCollectionType(List.class, DemoClass.class);
try {
return mapper.readValue(json, type);
} catch (Exception e) {
throw failure(e, "Unable to unmarshall the string " + json
+ "into " + clazz);
}
}
}
我的dynamoDb类
@DynamoDBAttribute
@DynamoDBMarshalling(marshallerClass = MyCustomMarshaller.class)
List<DemoClass> Object;
DemoClass
public class DemoClass {
String name;
int id;
}
所有代码都运行良好。事情是
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling是 的弃用
那么如何在不使用此dynamoDBmarshalling的情况下更改代码?
先谢谢,
杰
答案 0 :(得分:0)
是的,您应该使用DynamoDBTypeConverter
您可以从here
复制我的代码为了完整性,这里是我在链接答案中使用的示例
// 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; }
@DynamoDBTypeConverted(converter = MyObjectConverter.class)
public List<MyObject> getObjects() { return this.objects; }
public void setObjects(List<MyObject> objects) { this.objects = objects; }
}
-
public class MyObjectConverter implements DynamoDBTypeConverter<String, List<MyObject>> {
@Override
public String convert(List<Object> objects) {
//Jackson object mapper
ObjectMapper objectMapper = new ObjectMapper();
try {
String objectsString = objectMapper.writeValueAsString(objects);
return objectsString;
} catch (JsonProcessingException e) {
//do something
}
return null;
}
@Override
public List<Object> unconvert(String objectssString) {
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Object> objects = objectMapper.readValue(objectsString, new TypeReference<List<Object>>(){});
return objects;
} catch (JsonParseException e) {
//do something
} catch (JsonMappingException e) {
//do something
} catch (IOException e) {
//do something
}
return null;
}
}
答案 1 :(得分:0)
另一种更易于实现的方法,让DynamoDB在幕后处理转换。
将字段注释为@DynamoAttribute
@DynamoDBAttribute
private MyObjectClass myObject;
然后,您用@DynamoDBDocument注释“ MyObjectClass”
@DynamoDBDocument
public class MyObjectClass {
....
}
并且DynamoDB会将“ MyObjectClass myObject”转换和取消转换为JSON形状,即使它是对象的列表/数组也是如此。