'Serialize HashMap with object keys with Gson
I am writing some code to serialize a neural network system I have developed. This system has a "database" that keeps track of the evolution of the neural networks, and it does so by storing the ID of each gene in a HashMap with a GeneKey, which is a record containing the ID of the gene before and the ID of the gene after the gene we're storing.
A HashMap with some data looks like this:
existingNodes = {
GeneKey[a=0, b=3] = 4,
GeneKey[a=1, b=4] = 5
}
Everything in the system serializes fine, except this HashMap, because Json can only have numbers and strings as its keys, and in my HashMap I'm using objects for the keys. Is there an easy way to serialize this to json using Gson?
Edit: This is how the HashMap is constructed:
HashMap<GeneKey, Integer> existingNodes = new HashMap<>();
existingNodes.put(new GeneKey(0, 3), 4);
existingNodes.put(new GeneKey(1, 4), 5);
System.out.println("existingNodes = "+registry);
//existingNodes = {
// GeneKey[a=0, b=3] = 4,
// GeneKey[a=1, b=4] = 5
//}
This is the GeneKey class:
public record GeneKey(int a, int b) {}
Solution 1:[1]
It would be helpful if you could give the JSON string which you got after serializing using Gson.
However, please check the following code if this solves your issue.
Define GenKey class with overriden hashCode and equals methods as:
public class GeneKey {
private int a;
private int b;
public GeneKey(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + a;
result = prime * result + b;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GeneKey other = (GeneKey) obj;
if (a != other.a)
return false;
if (b != other.b)
return false;
return true;
}
@Override
public String toString() {
//return "GeneKey [a=" + a + ", b=" + b + "]";
// Updated for deserialization using Gson
Gson gson = new
GsonBuilder().serializeNulls().disableHtmlEscaping().create();
return gson.toJson(this);
}
}
Now try to convert the HashMap with GenKey as key into JSON String using Gson :
HashMap<GeneKey, Integer> existingNodes = new HashMap<>();
existingNodes.put(new GeneKey(0, 3), 4);
existingNodes.put(new GeneKey(1, 4), 5);
Gson gson = new
GsonBuilder().serializeNulls().disableHtmlEscaping().create();
System.out.println(gson.toJson(existingNodes));
This is the output which I received in my console:
{"{\"a\":0,\"b\":3}":4,"{\"a\":1,\"b\":4}":5}
Updating the answer to add deserialization logic if required:
//Say, we pass the serialized JSON as a payload to some REST API. We can deserialize the Key of the response as follows -
@PostMapping("/getJson")
public Map<GeneKey, Integer> getJson(@RequestBody Map<String, Integer> response) {
final Gson gson = new Gson();
Map<GeneKey, Integer> deserializedMap = new HashMap<GeneKey,
Integer>();
response.keySet().forEach( k -> {
GeneKey key = gson.fromJson(k, GeneKey.class);
deserializedMap.put(key, response.get(k));
});
System.out.println(deserializedMap);
return deserializedMap;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
