ダリsārib:
私は、JSONに解析する必要がHashMapを持っています:
HashMap<String, Integer> worders = new HashMap<>();
私は、オブジェクトのJSON配列にそれを解析する必要があります。現在の値:
{"and": 100},
{"the": 50}
必要なJSON形式:
[
{"word": "and",
"count": 100},
{"word": "the",
"count": 50}
]
私は私が正しい形式にそれを置くためにループを使用する必要があることに気づいているが、確かではないどこか、どのように開始します。
私はまた、しかし、それは、フォーマットを修正する助けに感謝しない、JSONとしてそれを書くために)(ObjectMapperを使用しています。
ティムBiegeleisen:
あなたが実際にこれを行うには、正式な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);