首页 > 解决方案 > HashMap 到 Json 数组对象 - Java

问题描述

我有一个 HashMap,需要将其解析为 JSON:

HashMap<String, Integer> worders = new HashMap<>();

我需要将其解析为 JSON 对象数组。当前值:

{"and": 100},
{"the": 50}

需要的 JSON 格式:

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

我意识到我需要使用循环将其转换为正确的格式,但不确定从何处或如何开始。

我还使用 ObjectMapper() 将其编写为 JSON,但是,格式不正确,谢谢帮助。

标签: javajsonloopshashmap

解决方案


您实际上不需要创建正式的 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);

推荐阅读