JSON多层嵌套复杂结构数据扁平化处理转为行列数据
背景
公司的中台产品,需要对外部API接口返回的JSON数据进行采集入湖,有时候外部API接口返回的JSON数据层级嵌套比较深,举个栗子:

上述的JSON数据中,最外层为请求返回对象,data里面包含返回的业务数据,业务数据按照学校 / 班级 / 学生进行嵌套
在数据入湖时,需要按照最内层的学生视角将数据拆分为行列数据,最终的拆分结果如下:

由于对接的外部API接口返回的JSON数据结构不是统一的、固定的,所以需要通过一种算法对每一层对象、数组进行遍历和钻取,实现JSON数据的扁平化
网上找了一些JSON扁平化的中间件,例如:Json2Flat在扁平化处理过程不太完美,不支持跨层级的数组嵌套结构
所以决定自己实现扁平化处理
关键代码如下:
public class LinkedNode {
private LinkedNode parent;
private String parentName;
private Map<String, Object> data;
public LinkedNode(LinkedNode parent, String parentName, Map<String, Object> data) {
this.parent = parent;
this.parentName = parentName;
this.data = data;
}
}
public class JSONFlatProcessor {
private LinkedList<LinkedNode> nodes;
private LinkedList<String> column;
private List<Object[]> data;
public void find(LinkedNode parent, String parentName, Map<String, Object> data) {
LinkedNode node = new LinkedNode(parent, parentName, data);
if (!hasObjectOrArray(data)) {
nodes.add(node);
} else {
for (Map.Entry entry : data.entrySet()) {
if (entry.getValue() instanceof Map) {
find(node, String.valueOf(entry.getKey()), (Map<String, Object>) entry.getValue());
} else if (isObjectArray(entry.getValue())) {
find(node, String.valueOf(entry.getKey()), (List<Map<String, Object>>) entry.getValue());
}
}
}
}
public void find(LinkedNode parent, String parentName, List<Map<String, Object>> data) {
for (Map<String, Object> item : data) {
find(parent, parentName, item);
}
}
protected Boolean hasObjectOrArray(Map<String, Object> item) {
Object field;
for (Map.Entry entry : item.entrySet()) {
field = entry.getValue();
if (field instanceof Map || isObjectArray(field)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
protected Boolean isObjectArray(Object object) {
return object instanceof List
&& !CollectionUtils.isEmpty((List) object)
&& ((List) object).get(0) instanceof Map;
}
public JSONFlatProcessor process(List<Map<String, Object>> data) {
nodes = new LinkedList<>();
find(null, null, data);
return this;
}
public JSONFlatProcessor process(Map<String, Object> data) {
nodes = new LinkedList<>();
find(null, null, data);
return this;
}
public LinkedList<LinkedNode> getNodes() {
return nodes;
}
public List<String> getColumn() {
if (CollectionUtils.isEmpty(nodes)) {
return Collections.emptyList();
}
column = new LinkedList<>();
collectColumn(nodes.getFirst());
return column;
}
protected void collectColumn(LinkedNode node) {
List<String> innerColumn = new ArrayList<>(node.getData().size());
String columnBuilder;
for (Map.Entry entry : node.getData().entrySet()) {
if (!(entry.getValue() instanceof Map || isObjectArray(entry.getValue()))) {
columnBuilder = null == node.getParentName()? String.valueOf(entry.getKey()) : String.format("%s.%s", node.getParentName(), entry.getKey());
innerColumn.add(columnBuilder);
}
}
column.addAll(0, innerColumn);
if (null != node.getParent()) {
collectColumn(node.getParent());
}
}
public List<Object[]> getData() {
if (CollectionUtils.isEmpty(nodes)) {
return Collections.emptyList();
}
data = new ArrayList<>(nodes.size());
LinkedList<Object> container;
for (LinkedNode node : nodes) {
container = new LinkedList<>();
collectData(node, container);
data.add(container.toArray());
}
return data;
}
protected void collectData(LinkedNode node, LinkedList<Object> container) {
List<Object> innerData = new ArrayList<>(node.getData().size());
for (Map.Entry entry : node.getData().entrySet()) {
if (!(entry.getValue() instanceof Map || isObjectArray(entry.getValue()))) {
innerData.add(entry.getValue());
}
}
container.addAll(0, innerData);
if (null != node.getParent()) {
collectData(node.getParent(), container);
}
}
protected static class CollectionUtils {
public static boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
}
}
public class MainTests {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"code\":200,\"requestId\":\"1680177848458\",\"data\":[{\"school\":\"xxx市第一实验小学\",\"no\":\"1001\",\"class\":[{\"name\":\"一(1)班\",\"teacher\":\"吴老师\",\"student\":[{\"name\":\"张同学\",\"age\":6},{\"name\":\"王同学\",\"age\":7}]}]},{\"school\":\"xxx市第二实验小学\",\"no\":\"1002\",\"class\":[{\"name\":\"一(2)班\",\"teacher\":\"陈老师\",\"student\":[{\"name\":\"欧阳同学\",\"age\":6}]}]}]}";
ObjectMapper jsonMapper = new ObjectMapper();
// List<Map<String, Object>> map = jsonMapper.readValue(jsonStr, List.class);
Map<String, Object> map = jsonMapper.readValue(jsonStr, Map.class);
JSONFlatProcessor processor = new JSONFlatProcessor().process(map);
System.out.println("数据条数: " + processor.getNodes().size());
System.out.println("字段名: " + processor.getColumn());
System.out.println("首行数据: " + new ObjectMapper().writeValueAsString(processor.getData().get(0)));
}
}
数据条数: 3
字段名: [code, requestId, data.school, data.no, class.name, class.teacher, student.name, student.age]
首行数据: [200,"1680177848458","xxx市第一实验小学","1001","一(1)班","吴老师","张同学",6]
JSON多层嵌套复杂结构数据扁平化处理转为行列数据的更多相关文章
- 【SpringBoot】 Java中如何封装Http请求,以及JSON多层嵌套解析
前言 本文中的内容其实严格来说不算springboot里面的特性,属于JAVA基础,只是我在项目中遇到了,特归纳总结一下. HTTP请求封装 目前JAVA对于HTTP封装主要有三种方式: 1. JAV ...
- Json多层嵌套,要怎么提取?
一直用Jmeter的Json Extactor,对于多层的Json嵌套,很好用,自己写代码的时候,总是遇到各种Exception 看了网上的资料,整理一下 1. 最简单的JSON提取,只有一层的时候 ...
- mybatis 注解写法 多层嵌套foreach,调用存储过程,批量插入数据
@Select("<script>" + "DECLARE @edi_Invoice_Details edi_Invoice_Details;" + ...
- 【JS简洁之道小技巧】第一期 扁平化数组
介绍两种方法,一是ES6的flat,简单粗暴.二是递归,也不麻烦. flat ES6自带了flat方法,用于使一个嵌套的数组扁平化,默认展开一个嵌套层.flat方法接收一个数字类型参数,参数值即嵌套层 ...
- ASP.NET提取多层嵌套json数据的方法
本文实例讲述了ASP.NET利用第三方类库Newtonsoft.Json提取多层嵌套json数据的方法,具体例子如下. 假设需要提取的json字符串如下: {"name":&quo ...
- .net(c#)提取多层嵌套的JSON
Newtonsoft.Json.Net20.dll 下载请访问http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar 在.net 2.0中提 ...
- [转]easyui tree 模仿ztree 使用扁平化加载json
原文地址:http://my.oschina.net/acitiviti/blog/349377 参考文章:http://www.jeasyuicn.com/demo/treeloadfilter.h ...
- c#多层嵌套Json
Newtonsoft.Json.Net20.dll 下载请访问http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar 在.net 2.0中提 ...
- 提取多层嵌套Json数据
在.net 2.0中提取这样的json {"name":"lily","age":23,"addr":{"ci ...
- 多层嵌套的json数据
很多时候我们见到的json数据都是多层嵌套的,就像下面这般: {"name":"桔子桑", "sex":"男", , & ...
随机推荐
- 形象谈JVM-第二章-认识编译器
我在上一章<形象谈JVM-第一章-认识JVM>提到的"翻译",其实就是我们今天所说的"编译"的概念. 上一章原文链接:https://www.cnb ...
- ABP Framework 7.4 RC 新增功能简介:增强微服务架构支持
ABP Framework 版本号:7.4.0-rc.1 发布时间:2023.8.16 阅读原文:ABP.IO Platform 7.4 RC Has Been Published 翻译:iEricL ...
- zbolg首页-文章内标签调用代码
{if count($lhantItem.Tags)>0}{foreach $lhantItem.Tags as $i => $tag} <a href='{$tag.Url}' t ...
- Python爬虫——爬虫时如何知道是否代理ip伪装成功?
在进行爬虫时,我们可能需要使用代理IP来伪装自己的身份,以避免被网站封禁.如何判断代理IP是否伪装成功呢?本篇文章将围绕这个问题展开讲解,同时提供Python代码示例. 1. 确认代理IP地址 首先, ...
- 【AI 模型】首个 Joy 模型诞生!!!全民生成 Joy 大片
接上一篇文章 "只要10秒,AI生成IP海报,解放双手",这次是全网第一个"共享joy模型",真的赚到了! 经过这段时间无数次的探索.试错.实验,最终积累了非常 ...
- Linux系列教程——Linux发展介绍、Linux系统安装、查看Linux内核版本和系统版本、Centos7安装jdk1.8
文章目录 1 Linux发展介绍 零 什么是Linux 一 Linux前身 二 Linux诞生 三 开源文化 四 Linux系统特点 五 Linux分支 2 Linux系统安装 Linux虚拟机安装 ...
- python第2~5章 学习笔记
# 第2~5章 学习笔记 ## 什么是计算机语言 计算机就是一台用来计算机的机器,人让计算机干什么计算机就得干什么! 需要通过计算机的语言来控制计算机(编程语言)! 计算机语言其实和人类的语言没有本质 ...
- How to install Django¶
This document will get you up and running with Django. Install Python Being a Python Web framework, ...
- python接口自动化 之excel读取测试数据
一.当你拥有一个excel版的接口用例 excel中有用例名称.url.请求方式和请求参数 二.获取excel的Url.请求方式和请求参数 # 单独获取某个单元格的值,第二行第二列# 第二行数据 ro ...
- 为什么 CSS flex 布局中没有 `justify-items` 和 `justify-self`?
为什么 CSS flex 布局中没有 justify-items 和 justify-self? 为什么在 CSS flex 布局中存在 align-items 和 align-self,却没有 ju ...