gpt4 book ai didi

java - HashMap 到 Json 数组对象 - Java

转载 作者:搜寻专家 更新时间:2023-11-01 02:57:05 35 4
gpt4 key购买 nike

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

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

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

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

需要的 JSON 格式:

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

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

我也使用了 ObjectMapper() 将其写成 JSON,但是,这不正确的格式,感谢您的帮助。

最佳答案

您实际上不需要创建正式的 Java 类来执行此操作。我们可以尝试创建一个 ArrayNode,然后添加代表原始 HashMap 中每个条目的子 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);

关于java - HashMap 到 Json 数组对象 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53580559/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com