Right now I'm attempting to write out words and their scores in JSON, however actually writing them is proving to be rather arduous. My code to write things out is relatively simple, and would work if it was just a single value, however I need to access the values over and over.
Here is the code I use to write:
public void write(String word) throws IOException {
ValuedWord valuedWord = new ValuedWord(0,0,0,0,0,0,0,0);
writer.withRootName(word).writeValue(generator, valuedWord);
}
This should ideally yield something along the lines of this:
{
"WORD_A" : {
"SCORE_1" : 0,
"SCORE_2" : 0
},
"WORD_B" : {
"SCORE_1" : 0,
"SCORE_2" : 0
}
}
However, the formatting seems to become quite odd when I do a second word, turning into two separate levels instead of staying on the same level:
{
"no" : {
"joy" : 0.0,
"anger" : 0.0,
"sadness" : 0.0,
"fear" : 0.0,
"love" : 0.0,
"disliking" : 0.0,
"liking" : 0.0,
"uses" : 0
}
} {
"yes" : {
"joy" : 0.0,
"anger" : 0.0,
"sadness" : 0.0,
"fear" : 0.0,
"love" : 0.0,
"disliking" : 0.0,
"liking" : 0.0,
"uses" : 0
}
}
It also does not help that every time I write to the file, it immediately deletes everything that already exists.
How would I append data to the JSON file, on the same level, and just edit pre-existing data?
You can keep adding ValuedWord
objects to a map with keys as word
and after creation of all ValuedWord
objects, serialize to JSON.
Sample code:
ValuedWord valuedWord1 = new ValuedWord(0,0,0,0,0,0,0,0);
ValuedWord valuedWord2 = new ValuedWord(0,2,3,0,0,0,0,0);
Map<String, ValuedWord> map = new HashMap<String, ValuedWord>();
map.put("WORD1", valuedWord1);
map.put("WORD2", valuedWord2);
String mapJson = objectMapper.writeValueAsString(map);