背景

公司的中台产品,需要对外部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多层嵌套复杂结构数据扁平化处理转为行列数据的更多相关文章

  1. 【SpringBoot】 Java中如何封装Http请求,以及JSON多层嵌套解析

    前言 本文中的内容其实严格来说不算springboot里面的特性,属于JAVA基础,只是我在项目中遇到了,特归纳总结一下. HTTP请求封装 目前JAVA对于HTTP封装主要有三种方式: 1. JAV ...

  2. Json多层嵌套,要怎么提取?

    一直用Jmeter的Json Extactor,对于多层的Json嵌套,很好用,自己写代码的时候,总是遇到各种Exception 看了网上的资料,整理一下 1. 最简单的JSON提取,只有一层的时候 ...

  3. mybatis 注解写法 多层嵌套foreach,调用存储过程,批量插入数据

    @Select("<script>" + "DECLARE @edi_Invoice_Details edi_Invoice_Details;" + ...

  4. 【JS简洁之道小技巧】第一期 扁平化数组

    介绍两种方法,一是ES6的flat,简单粗暴.二是递归,也不麻烦. flat ES6自带了flat方法,用于使一个嵌套的数组扁平化,默认展开一个嵌套层.flat方法接收一个数字类型参数,参数值即嵌套层 ...

  5. ASP.NET提取多层嵌套json数据的方法

    本文实例讲述了ASP.NET利用第三方类库Newtonsoft.Json提取多层嵌套json数据的方法,具体例子如下. 假设需要提取的json字符串如下: {"name":&quo ...

  6. .net(c#)提取多层嵌套的JSON

    Newtonsoft.Json.Net20.dll 下载请访问http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar 在.net 2.0中提 ...

  7. [转]easyui tree 模仿ztree 使用扁平化加载json

    原文地址:http://my.oschina.net/acitiviti/blog/349377 参考文章:http://www.jeasyuicn.com/demo/treeloadfilter.h ...

  8. c#多层嵌套Json

    Newtonsoft.Json.Net20.dll 下载请访问http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar 在.net 2.0中提 ...

  9. 提取多层嵌套Json数据

    在.net 2.0中提取这样的json {"name":"lily","age":23,"addr":{"ci ...

  10. 多层嵌套的json数据

    很多时候我们见到的json数据都是多层嵌套的,就像下面这般: {"name":"桔子桑", "sex":"男", , & ...

随机推荐

  1. css里的position的static|relative|absolute|fixed的区别

    前提:仅以div块为例,其它不清楚 注:1.下面截图看起来不是从页面左上角位置开始,是因为body元素有默认的margin,有边框 2.当position不是static时,top和bottom需要指 ...

  2. Web通用漏洞--文件包含

    Web通用漏洞--文件包含 文件包含原理 在项目开发过程中,开发人员通常会将重复使用的函数写入单个文件中,在使用该类函数时,直接调用文件即可,无需重新编写,这种调用文件的过程成为文件包含.在文件包含过 ...

  3. 【pandas小技巧】--category类型补充

    category类型在pandas基础系列中有一篇介绍数据类型的文章中已经介绍过.category类型并不是python中的类型,是pandas特有的类型. category类型的优势那篇文章已经介绍 ...

  4. API接口的重要性

    API接口的重要性在现代软件开发中无可替代.以下是API接口的几个重要方面: 1. 实现系统集成:API接口允许不同应用程序之间实现数据共享和交流.通过API接口,不同的软件系统可以相互连接和协作,实 ...

  5. JS遍历Json串并获取Key和Value

    //data为json串 for (var key in data) { console.log(key); console.log(data[key]); }

  6. Solution -「洛谷 P4007」小 Y 和恐怖的奴隶主

    Description Link. 这道题 的加强版. Solution 题解里面大多数都是概率 DP,或者是期望 DP 然后是逆推.甚至不给 DP 的转移式.机房 yyds Reanap 发了一篇逆 ...

  7. Python基于Flask的高校舆情分析,舆情监控可视化系统

    一.前言在当今社会,舆情监控越来越被重视.随着互联网技术的发展,我们从传统媒体渠道.官方报告.调查问卷等方式搜集到的舆情信息,逐渐被网络上的内容所替代.因为网络上的内容传播速度快.及时性强.覆盖范围广 ...

  8. 2023-09-30:用go语言,给你一个整数数组 nums 和一个整数 k 。 nums 仅包含 0 和 1, 每一次移动,你可以选择 相邻 两个数字并将它们交换。 请你返回使 nums 中包含 k

    2023-09-30:用go语言,给你一个整数数组 nums 和一个整数 k . nums 仅包含 0 和 1, 每一次移动,你可以选择 相邻 两个数字并将它们交换. 请你返回使 nums 中包含 k ...

  9. C++ 对拍详解 和解读

    对拍是什么# ​对拍,是一个比较实用的工具.它能够非常方便地对于两个程序的输出文件进行比较,可以帮助我们实现一些自动化的比较输出结果的问题. ​众所周知,几乎每一道编程题目,都会有某种正解能拿到满分: ...

  10. c语言代码练习4(改进)

    #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <string.h> #include <wi ...