Skip to content
Advertisement

How can I store nested Hashmap in Redis?

I want to store netsted HashMap in Redis having single key.

For example :

HashMap<String, HashMap<String,String>> map = new  HashMap<>();

Please Suggest :

  • Is there any way to store the above-mentioned data structure?
  • How can we achieve this?

Advertisement

Answer

Redis doesn’t support it as of now. However there is a way to do it, other than rejson.

You can convert it into JSON and store in Redis and retrieve. Following utility methods, which I use in Jackson.

To convert Object to String :

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;
}

Example : stringify(obj);

To convert String to 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;
    }
}

Example : List<Object> list = objectify("Your Json", new TypeReference<List<Object>>(){})

You can update this method as per your requirement. I am sure, you know, how to add and update in Redis.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement