Search code examples
javaamazon-dynamodb

DynamoDB - Object to AttributeValue


I'm aware of DynamoDBMapper but in my case I can't use it because I don't know all the attributes beforehand.

I have a JSON and it's parsed to a map of objects by using Jackson parser:

Map<String, Object> userData = mapper.readValue(new File("user.json"), Map.class);

Looping through each attribute, how can I convert the value to AttributeValue given that DynamoDB AttributeValue supports Boolean, String, Number, Bytes, List, etc.

Is there an efficient way to do this? Is there a library for this already? My naive approach is to check if each value is of type Boolean/String/Number/etc. and then call the appropriate AttributeValue method, e.g: new AttributeValue().withN(value.toString()) - which gives me long lines of if, else if


Solution

  • Finally figured out by looking at how AWS parses the JSON

    Basically, this is the code:

        Item item = new Item().withJSON("document", jsonStr);
        Map<String,AttributeValue> attributes = InternalUtils.toAttributeValues(item);
        return attributes.get("document").getM();
    

    Very neat.