I'm saving a score (KillcountRatio class) to a name (String) in a HashMap that I am saving with Jackson JSON, but when loading the saved json file, it is unable to cast the KillCountRatio class value stored in the HashMap with a certain key to KillCountRatio, it gives
java.util.LinkedHashMap cannot be cast to KillCountRatio
because the value stored in the HashMap is no longer a KillCountRatio, rather is a LinkedHashMap.
Not sure what to try.
Here is KillCountRatio class:
public final class KillCountRatio {
private int killCount;
private int deathCount;
}
Here is the HashMap where the above is stored and given a String key and then saved with Jackson JSON.
private HashMap<String, KillCountRatio> savedScores = new HashMap<>();
saving and loading:
public void save() {
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
File f = new File("data/savedScores.json");
try {
writer.writeValue(f, savedScores); //written here
} catch (IOException e) {
e.printStackTrace();
}
}
public void load() {
savedScores = new ObjectMapper().readValue(new File("data/savedScores.json"), new HashMap<String, KillCountRatio>().getClass());
}
This is the error:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.datarepo.KillCountRatio
What can I do to overcome this casting error? Some examples using the above code of how I can get this to work would be appreciated.
I tried this deserializer with the load method and it still gave the same error:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(KillCountRatio.class, new KillCountRatioDeserializer());
mapper.registerModule(module);
I also tried annotating the KillCountRatio class with this:
@JsonDeserialize(using = KillCountRatioDeserializer.class)