BPm*_*BPm 8 java amazon-dynamodb
我知道DynamoDBMapper,但在我的情况下我不能使用它,因为我事先并不知道所有的属性.
我有一个JSON,它通过使用Jackson解析器解析为对象的映射:
Map<String, Object> userData = mapper.readValue(new File("user.json"), Map.class);
Run Code Online (Sandbox Code Playgroud)
循环遍历每个属性,如何将值转换为AttributeValue给定的DynamoDB AttributeValue支持布尔值,字符串,数字,字节,列表等.
有没有一种有效的方法来做到这一点?这个库已经有了吗?我天真的方法是检查每个值是否为Boolean/String/Number/etc类型.然后调用适当的AttributeValue方法,例如:new AttributeValue().withN(value.toString())- 这给了我很长的一行if, else if
BPm*_*BPm 34
基本上,这是代码:
Item item = new Item().withJSON("document", jsonStr);
Map<String,AttributeValue> attributes = InternalUtils.toAttributeValues(item);
return attributes.get("document").getM();
Run Code Online (Sandbox Code Playgroud)
井井有条.
小智 5
以下是一个简单的解决方案,可用于将任何DynamoDB Json转换为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;
}
Run Code Online (Sandbox Code Playgroud)
这将产生您所需的Json,其形式List<Map<String,Object>>为的子集object。
我用JacksonConverterImpl转换JsonNode为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);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
谢谢,周杰伦
| 归档时间: |
|
| 查看次数: |
16204 次 |
| 最近记录: |