- 引入依赖
<!--依赖 -->
<dependency>
<groupId>com.github.wnameless.json</groupId>
<artifactId>json-flattener</artifactId>
<version>0.16.4</version>
</dependency>
- demo
public static void main(String[] args) {
String jsonStr = "";
jsonStr = FileUtil.readUtf8String("x.json");
// 扁平化,深层次的json结构转成key-value
Map<String, Object> flatJson = JsonFlattener.flattenAsMap(jsonStr);
flatJson.entrySet().forEach(System.out::println);
// 去扁平化,还原深层次的json
String unFlatten = JsonUnflattener.unflatten(flatJson);
// 扁平化级别默认.隔开,withSeparator 指定分割符
JsonFlattener jsonFlattener = new JsonFlattener(jsonStr);
Map<String, Object> map = jsonFlattener.withSeparator('-').flattenAsMap();
}
- 效果
# 原始json
{
"code": 200,
"data": [
{
"no": "1001",
"school": "xxx市第一实验小学",
"class": [
{
"student": [
{
"name": "张同学",
"age": 6
},
{
"name": "王同学",
"age": 7
}
],
"teacher": "吴老师",
"name": "一(1)班"
}
]
},
{
"no": "1002",
"school": "xxx市第二实验小学",
"class": [
{
"student": [
{
"name": "欧阳同学",
"age": 6
}
],
"teacher": "陈老师",
"name": "一(2)班"
}
]
}
],
"requestId": "1680177848458"
}
# 扁平化
code=200
requestId=1680177848458
data[0]-school=xxx市第一实验小学
data[0]-no=1001
data[0]-class[0]-name=一(1)班
data[0]-class[0]-teacher=吴老师
data[0]-class[0]-student[0]-name=张同学
data[0]-class[0]-student[0]-age=6
data[0]-class[0]-student[1]-name=王同学
data[0]-class[0]-student[1]-age=7
data[1]-school=xxx市第二实验小学
data[1]-no=1002
data[1]-class[0]-name=一(2)班
data[1]-class[0]-teacher=陈老师
data[1]-class[0]-student[0]-name=欧阳同学
data[1]-class[0]-student[0]-age=6
# 去扁平化
{
"code": 200,
"data": [
{
"no": "1001",
"school": "xxx市第一实验小学",
"class": [
{
"student": [
{
"name": "张同学",
"age": 6
},
{
"name": "王同学",
"age": 7
}
],
"teacher": "吴老师",
"name": "一(1)班"
}
]
},
{
"no": "1002",
"school": "xxx市第二实验小学",
"class": [
{
"student": [
{
"name": "欧阳同学",
"age": 6
}
],
"teacher": "陈老师",
"name": "一(2)班"
}
]
}
],
"requestId": "1680177848458"
}
标签:Java,扁平化,age,Json,student,data,class,name
From: https://www.cnblogs.com/qqkkOvO/p/17563387.html