您可以获取JSON,JsonNode
并递归遍历所有字段,然后将键和值字段添加到Map。当值是对象而不是字符串时,您可以将字段名称添加到List中,以最终遇到字符串时使用句点进行连接。首先创建(为了提高可读性)将Json字段添加到的单独方法Map
:
void mapAppender(Map<String, String> result, Entry<String, JsonNode> node, List<String> names) {
names.add(node.getKey());
if (node.getValue().isTextual()) {
String name = names.stream().collect(joining("."));
result.put(name, node.getValue().asText());
} else {
node.getValue().fields()
.forEachRemaining(nested -> mapAppender(result, nested, new ArrayList<>(names)));
}
}
并像这样使用它:
ObjectMapper mapper = new ObjectMapper();
Map<String, String> result = new HashMap<>();
mapper.readTree(json).fields()
.forEachRemaining(node -> mapAppender(result, node, new ArrayList<String>()));
当fields()
返回Iterator
。谨防StackOverflowErrors
深度嵌套的JSON可能会降低性能。