DynamoDB - Object to AttributeValue
I am aware of DynamoDBMapper, but in my case I cannot use it because I do not know all the attributes in advance.
I have JSON and it is parsed into a featuremap using a parser Jackson
:
Map<String, Object> userData = mapper.readValue(new File("user.json"), Map.class);
Quoting through each attribute how can I convert the value to AttributeValue
, given DynamoDB AttributeValue
supports Boolean, String, Number, Bytes, List, etc.
Is there an efficient way to do this? Is there a library for this? My naive approach is to check if each value is of type Boolean / String / Number / etc. and then call the appropriate method AttributeValue
like: new AttributeValue().withN(value.toString())
- which gives me long linesif, else if
source to share
Finally figured out how AWS parses 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.
source to share
Below is a simple solution that can be applied to convert any DynamoDB Json to Simple JSON.
//passing the reponse.getItems()
public static Object getJson(List<Map<String,AttributeValue>> mapList) {
List<Object> finalJson= new ArrayList();
for(Map<String,AttributeValue> eachEntry : mapList) {
finalJson.add(mapToJson(eachEntry));
}
return finalJson;
}
//if the map is null then it add the key and value(string) in the finalKeyValueMap
public static Map<String,Object> mapToJson(Map<String,AttributeValue> keyValueMap){
Map<String,Object> finalKeyValueMap = new HashMap();
for(Map.Entry<String, AttributeValue> entry : keyValueMap.entrySet())
{
if(entry.getValue().getM() == null) {
finalKeyValueMap.put(entry.getKey(),entry.getValue().getS());
}
else {
finalKeyValueMap.put(entry.getKey(),mapToJson(entry.getValue().getM()));
}
}
return finalKeyValueMap;
}
This will create the desired Json in a view List<Map<String,Object>>
that is a subset of object
.
source to share