我想将网式HashMap
存储在具有单个键的Redis
中。
例如 :
HashMap<String, HashMap<String,String>> map = new HashMap<>();
请建议:
最佳答案
Redis目前不支持它。但是,除了rejson
之外,还有其他方法可以做到。
您可以将其转换为JSON并存储在Redis中并进行检索。以下是我在Jackson中使用的实用程序方法。
要将对象转换为字符串:
public static String stringify(Object object) {
ObjectMapper jackson = new ObjectMapper();
jackson.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
try {
return jackson.writeValueAsString(object);
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Error while creating json: ", ex);
}
return null;
}
示例:
stringify(obj);
要将String转换为Object:
public static <T> T objectify(String content, TypeReference valueType) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
dateFormat.setTimeZone(Calendar.getInstance().getTimeZone());
mapper.setDateFormat(dateFormat);
return mapper.readValue(content, valueType);
} catch (Exception e) {
LOG.log(Level.WARNING, "returning null because of error : {0}", e.getMessage());
return null;
}
}
示例:
List<Object> list = objectify("Your Json", new TypeReference<List<Object>>(){})
您可以根据需要更新此方法。我相信,您知道如何在Redis中添加和更新。