I declared a hashmap of key value pairs as,
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
I am using a method to serialize this hashmap and convert it into a string using the following code:
public static String serializeMetadata(HashMap<String, String> metadata) throws IOException {
try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(metadata);
return baos.toString();
}
}
When I call serializeMetadata method and pass my hashmap as input, I expect map state to be streamed by ObjectOutputStream(oos) and store array of bytes in ByteArrayOutputStream(baos). when a toString() is called with baos, I expect an output of
"{key1=value1, key2=value2, key3=value3}"
Just the same kind of output when we convert a hashmap to string. Instead, I get some not readable formatted string like,
���sr�java.util.HashMap���`��F� loadFactorI� thresholdxp?@�����������t�key1t�value1t�key2t�value2t�key3t�value3x
I understand, if I deserialize the baos, I get a hashmap again and if I do a toString(), I get the format I need.
I need a formatted string when serialized hashmap is converted to string, so, 1. I can write a unit test and assert hashmap for a string 2. Persist that string(that has all formatted keys and values) in DB for future data analysis. 3. I can call the string from DB in an application and deserialize it back to a hashmap and continue using the existing states.
I don't want a JSON string. Imagine all key value pairs of hashmap are stored in a single field of DB. I could not find the right solution to it, So if there are any duplicate links, please put them in comments. Any help is appreciated. Thanks!