gpt4 book ai didi

java - 在 @DynamoDBTable 中创建 List 而不使用 dynamodbmarshalling 的替代方法(已弃用)

转载 作者:行者123 更新时间:2023-11-30 06:18:30 25 4
gpt4 key购买 nike

我关注了here通过创建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 类(class)

@DynamoDBAttribute
@DynamoDBMarshalling(marshallerClass = MyCustomMarshaller.class)
List<DemoClass> Object;

演示类

public class DemoClass {

String name;

int id;

}

所有代码都运行良好。事实是

com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling is deprecated

那么如何在不使用此 dynamoDBmarshalling 的情况下更改代码?

提前致谢,
周杰伦

最佳答案

是的,您应该使用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;
}
}

关于java - 在 @DynamoDBTable 中创建 List<MyObject> 而不使用 dynamodbmarshalling 的替代方法(已弃用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48688807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com