创建List< MyObject>的替代方法在@DynamoDBTable中而不使用dynamodbmarshalling(已弃用)
问题描述:
通过创建 MyCustomMarshaller ,我们已经此处。
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;
}
所有代码都很好用。 / p>
All the codes were working great.By the thing is
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling为
已淘汰
那么我如何在不使用dynamoDBmarshalling的情况下更改代码?
So how can I change my code without using this dynamoDBmarshalling?
在此先感谢,
Jay
Thanks in Advance,
Jay
答
是的,您应该使用 DynamoDBTypeConverter
您可以从此处
此处复制我的代码是我在链接答案上使用的示例
For completeness here is the example I used on the linked answer
// 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;
}
}