简体   繁体   English

HashMap到Json数组对象 - Java

[英]HashMap to Json Array Object - Java

I have a HashMap which I need to parse into JSON: 我有一个HashMap,我需要解析为JSON:

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

I need to parse it into a JSON array of objects. 我需要将它解析为JSON对象数组。 Current values: 当前值:

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

Needed JSON format: 需要的JSON格式:

[
{"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. 我也使用ObjectMapper()将其写为JSON,但是,这不能纠正格式,谢谢你的帮助。

You don't actually need to create a formal Java class to do this. 实际上,您不需要创建正式的Java类来执行此操作。 We can try creating an ArrayNode , and then adding child JsonNode objects which represent each entry in your original hash map. 我们可以尝试创建一个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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM