栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

展平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可能会降低性能。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/515925.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号