I'm trying to save a HashMap
as a JSON file using Jackson.
I want said file to be located in my resources folder.
try {
new ObjectMapper().writeValue(
new File(MyClass.class.getResource("/path/file.json").toURI()), myHashMap);
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
I've tried this approach, which yields no Exceptions, but leaves me with a blank JSON file. No data gets written into it. Is this some permissions problem?
Also I want to read this file as a HashMap
.
This is my current approach:
Map<Long, String> tmp;
try {
tmp = new ObjectMapper().readValue(
MyClass.class.getResourceAsStream("/path/file.json"), Map.class);
} catch (IOException e) {
tmp = new HashMap<>();
}
myHashMap = tmp;
Are there any better ways to do so? To my understanding the exception is normally thrown when the file could not be found (Leaving actual errors out of the equation). Which is alright, just go with an empty HashMap
instead then. Since it will get populated later on and saved, so this case only exists when starting the program for the first time or when the file gets deleted.
Right now I'm mostly having trouble saving my file.