将HashMap转换为Json数组对象 - Java

5
我有一个HashMap需要解析成JSON格式:
HashMap<String, Integer> worders = new HashMap<>();

我需要将它解析成一个JSON对象数组。当前值:
{"and": 100},
{"the": 50}

所需的JSON格式:

[
{"word": "and",
"count": 100},
{"word": "the",
"count": 50}
]

我意识到需要使用循环将其放入正确的格式中,但不确定从哪里或如何开始。

我还使用了ObjectMapper()将其写成JSON,但这并没有纠正格式问题,谢谢帮助。


所以你想创建一个WordWithCount类,并用HashMap中的内容填充List<WordWithCount>,对吗?HashMap有一个entrySet()方法,它是所有条目的集合。因此,您可以循环并将每个条目转换为WordWithCount。阅读javadoc。尝试一些东西。 - JB Nizet
这里并不完全清楚你想要做什么。你是想将JSON格式的值打印到控制台上,还是将它们存储在数据结构中,或者是存储到文件中?请澄清一下。 - Matt Morgan
1个回答

3

你实际上不需要创建一个正式的Java类来完成这个操作。我们可以尝试创建一个ArrayNode,然后添加子JsonNode对象,代表原始哈希表中的每个条目。

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

非常感谢,这正是我所寻找的! - dali Sarib

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接