HashMap to Json Array Object - Java

dali Sarib :

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.

Tim Biegeleisen :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79128&siteId=1