5

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.

2
  • So you want to create a WordWithCount class, and populate a List<WordWithCount> with what your HashMap contains, right? HashMap has an entrySet() method, which is a set of all its entries. So you can loop over if and transform each entry into a WordWithCount. Read the javadoc. try something. Commented Dec 2, 2018 at 13:21
  • It's not entirely clear what you want to do here. Are you attempting to print out the JSON formatted values to the console, or store them in a data structure, or perhaps a file? Please clarify. Commented Dec 2, 2018 at 13:24

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, exactly what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.