2
votes

I have a simple POJO:

public class MyClass {
    public String id;
    public String name;
}

I want to serialize it to JSON equivalent to the format an AWS Lambda handler for DynamoDB events would get for en embedded document of DynamoDB type Map:

M: { 
    id= { S: "abc123", },
    name= { S: "whatever", },
}

And even more imporantly, I want to deserialize it from the JSON my Lambda function receives for every insert. The only examples I can find are very simple ones. None of them includes dealing with DynamoDB Maps in events inside of a Lambda handler.

I wonder if I have to write a serializer by hand or if there's something in the SDK I haven't found yet.

1

1 Answers

3
votes

You can map your POJO to an instance of com.amazonaws.services.dynamodbv2.model.AttributeValue and then serialize/deserialize it with GSON.

This is how to get started with Gson.

Below is an example of how to manipulate AttributeValue with Gson.

AttributeValue av1 = new AttributeValue("abc123");
AttributeValue av2 = new AttributeValue("whatever");
AttributeValue avM = new AttributeValue();
Map<String, AttributeValue> m = new HashMap<String, AttributeValue>();
m.put("id", av1);
m.put("name", av2);
avM.setM(m);
System.out.println(new Gson().toJson(avM));
// {"m":{"name":{"s":"whatever"},"id":{"s":"abc123"}}}

Map<String, Object> simpleMap = new HashMap<String, Object>();
simpleMap.put("id", "abc123");
simpleMap.put("name", "whatever");
AttributeValue avM2 = new AttributeValue().withM(InternalUtils.fromSimpleMap(simpleMap));
System.out.println(new Gson().toJson(avM2));
// {"m":{"name":{"s":"whatever"},"id":{"s":"abc123"}}}

String jsonStr = new Gson().toJson(avM2);
AttributeValue avM3 = new Gson().fromJson(jsonStr, AttributeValue.class);
System.out.println(avM3.getM().get("id").getS());
// abc123
System.out.println(avM3.getM().get("name").getS());
// whatever

If you are getting started with Lambda and DynamoDB with Java, I would suggest you to take a look at the Secure Pet Store.