您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

其他 2022/1/1 18:29:59 有395人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶