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, eg: new AttributeValue().withN(value.toString())
- which gives me long lines of if, else if
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.
Following is a simple solution which 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 produce your desired Json in the form of List<Map<String,Object>>
which is subset of the object
.
I used JacksonConverterImpl to convert JsonNode
to Map<String, AttributeValue>
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readValue(jsonString, JsonNode.class);
final JacksonConverter converter = new JacksonConverterImpl();
Map<String, AttributeValue> map = converter.jsonObjectToMap(jsonNode);
Hope this helps!
Thanks, Jay
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.