Search code examples
amazon-dynamodbamazon-dynamodb-streams

Removing null fields in the DynamoDB record


I am reading from a DynamoDB table in form of Map<String, AttributeValue>. The record looks something like this :-

{
    "name": {
        "s": "simran",
        "n": null,
        "b": null,
        "m": null,
        "l": null,
        "ss": null,
        "ns": null,
        "bs": null,
        "null": null,
        "bool": null
    },
    "id": {
        "s": "100",
        "n": null,
        "b": null,
        "m": null,
        "l": null,
        "ss": null,
        "ns": null,
        "bs": null,
        "null": null,
        "bool": null
    }
}

What i want to achieve is this :-

   {
        "name": {
            "S": "simran"
        },
        "id": {
            "S": "100"
        }
    }

The first JSON is extracted from this piece of code:-

com.amazonaws.services.dynamodbv2.model.Record inputRecord=  inputRecord.getDynamodb().getNewImage()

Is there a AWS SDK that could be used for to convert the first JSON to the second model ? If i use this toString(), I get the JSON of this format (with unnecessary trailing commas after the attribute value), making the json invalid for further parsing:- { "name": { "s": "simran", }, "id": { "s": "100", } }


Solution

  • I used RecordMapper to serialise the value. https://github.com/awslabs/dynamodb-streams-kinesis-adapter/blob/master/src/main/java/com/amazonaws/services/dynamodbv2/streamsadapter/model/RecordObjectMapper.java

    ObjectMapper objectMapper = new RecordObjectMapper();
    objectMapper.writeValueAsString()