java - 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,但是,格式不正确,谢谢帮助。
解决方案
您实际上不需要创建正式的 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);
推荐阅读
- git - 我可以从本地分支中删除目录,但将目录保留在远程存储库中吗
- php - 如何在wordpress搜索查询中用“”去除/替换倾斜的双引号?
- python - 如何使用numpy将0添加到列表列表的末尾?
- android - 更新表 2 的某些行时更新表 1 的 Sqlite 触发器
- python - Flask-SQLAlchemy - 检索 Query.all() - 每行中的所有列
- excel - 如何避免“下标超出范围?
- c# - 如何从任何 Cpu 项目中使用特定的本机 dll nuget
- c# - 在 Docker 中使用 System.Drawing
- bash - 为所有源文件添加自动标题注释
- python-3.x - 大文件中的字谜