展平JSON字符串以使包含每个级别键值的键映射到Map 使用Gson或Jackson

展平JSON字符串以使包含每个级别键值的键映射到Map 使用Gson或Jackson,第1张

展平JSON字符串以使包含每个级别键值的键映射到Map 使用Gson或Jackson

您可以获取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可能会降低性能。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5507042.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存