java - 如何将嵌套 JSONObject/JSONArray 转换为 flatJSON 并生成多条记录
问题描述
我想将嵌套的 JSONObject 转换为 flatJSON,如果 JSONAArray 存在,它必须生成多条记录。因此,我使用递归编写了代码,它将嵌套的 JSON 对象转换为 flatJSON。
public class Test {
public static Map<String,Object> flatJSON(Object obj,Map<String,Object> flatmap) {
Iterator<?> keys = ((JSONObject) obj).keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if(((JSONObject) obj).get(key) instanceof JSONObject) {
flatJSON(((JSONObject) obj).get(key), flatmap);
}
else if(((JSONObject) obj).get(key) instanceof JSONArray) {
if(((JSONObject) obj).getJSONArray(key).optJSONObject(0)!=null) {
JSONObject jsonObject = ((JSONObject) obj).getJSONArray(key).getJSONObject(0);
flatJSON(jsonObject, flatmap);
}
else {
flatmap.put(key, ((JSONObject) obj).get(key));
}
}
else {
flatmap.put(key, ((JSONObject) obj).get(key));
}
}
return flatmap;
}
public static void main(String[] args) {
String s="{\r\n" +
" \"root\": {\r\n" +
" \"data\": {\r\n" +
" \"a\": \"1\",\r\n" +
" \"b\": {\r\n" +
" \"c\": \"2\"\r\n" +
" },\r\n" +
" \"test\": [\r\n" +
" {\r\n" +
" \"e\": \"3\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"f\": \"4\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"test1\": [\r\n" +
" {\r\n" +
" \"g\": \"5\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"test2\": [\r\n" +
" 1,\r\n" +
" 2,\r\n" +
" 3\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
System.out.println(s);
System.out.println(flatJSON(new JSONObject(s), new HashMap<String, Object>()));
}
但是上面的代码仅适用于 JSONObject,对于 JSONArray 作为输入,我们如何转换为 flatJSON。以下是输入和预期输出的示例。
示例 1:
输入:
{
"root": {
"data": {
"a": "1",
"b": {
"c": "2"
},
"test": [
{
"e": "3",
"f": "5"
},
{
"e": "4",
"f": "6"
}
]
}
}
}
预期输出:
{
"a": "1",
"c": "2",
"e": "3",
"f": "5"
}
{
"a": "1",
"c": "2",
"e": "4",
"f": "6"
}
例 2:
输入:
{
"root": {
"data": {
"a": "1",
"b": {
"c": "2"
},
"test": [
{
"e": [{"m":1},{"m":2}]
},
{
"e": [{"m":3}]
}
]
}
}
}
预期输出:
{
"a": "1",
"c": "2",
"m": "1"
}
{
"a": "1",
"c": "2",
"m": "2"
}
{
"a": "1",
"c": "2",
"m": "3"
}
例 3:
输入:
{
"root": {
"data": {
"a": "1",
"b": {
"c": "2"
},
"test": [1,2,3]
}
}
}
预期输出:
{
"a": "1",
"c": "2",
"test": "1"
}
{
"a": "1",
"c": "2",
"test": "2"
}
{
"a": "1",
"c": "2",
"test": "3"
}
如何修改上述代码以获得预期结果。
解决方案
推荐阅读
- apache-spark - 使用 Spark 和 Jupyter Notebook 过滤、映射数据集中的问题
- google-cloud-platform - Cloud Sql 代理私有 IP 外部应用程序
- google-chrome - iframe 历史导航在 Chrome 中不起作用
- mysql - 如何使用mysql通过查询将逗号分隔的值拆分为多行
- javascript - Keycloak - 使用管理 API 通过循环向用户添加客户端角色
- node.js - NodeJS:SSH2 - 从流中读取最后 1000 个字母
- node.js - 如果已经使用 Docker 声明了环境变量,是否需要使用 dotenv
- algorithm - 匹配分数需求和供应量的算法
- android - Android - 如何检查抽屉布局中是否有任何项目被点击?
- javascript - 从 React 中的文件夹导入图像