Alternative way to create a <MyObject> list in @DynamoDBTable without using dynamodbmarshalling (deprecated)
I followed here by creating 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); } } } My dynamoDb class
@DynamoDBAttribute @DynamoDBMarshalling(marshallerClass = MyCustomMarshaller.class) List<DemoClass> Object; Democlass
public class DemoClass { String name; int id; } All codes worked perfectly. The fact is that
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling - this is deprecated
So, how can I change my code without using this dynamoDBmarshalling?
Thanks Advance,
Jay
+1
1 answer
Yes you should use DynamoDBTypeConverter
You can copy my code from here
For completeness, here is an example that I used for a related 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; } } 0