Reputation: 55
I have a HashMap which I need to parse into JSON:
HashMap<String, Integer> worders = new HashMap<>();
I need to parse it into a JSON array of objects. Current values:
{"and": 100},
{"the": 50}
Needed JSON format:
[
{"word": "and",
"count": 100},
{"word": "the",
"count": 50}
]
I have realised that I need to use a loop to put it into the correct format, but not sure where or how to start.
I have also used the ObjectMapper() to write it as JSON, however, that does not correct the format, thank for help.
Upvotes: 5
Views: 2594
Reputation: 521239
You don't actually need to create a formal Java class to do this. We can try creating an ArrayNode
, and then adding child JsonNode
objects which represent each entry in your original hash map.
HashMap<String, Integer> worders = new HashMap<>();
worders.put("and", 100);
worders.put("the", 50);
ObjectMapper mapper = new ObjectMapper();
ArrayNode rootNode = mapper.createArrayNode();
for (Map.Entry<String, Integer> entry : worders.entrySet()) {
JsonNode childNode = mapper.createObjectNode();
((ObjectNode) childNode).put("word", entry.getKey());
((ObjectNode) childNode).put("count", entry.getValue());
((ArrayNode) rootNode).add(childNode);
}
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(jsonString);
Upvotes: 3