ES6导出的mapping结构转为ES8的结构

发布于:2024-04-19 ⋅ 阅读:(34) ⋅ 点赞:(0)
package com.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 将ES6的Mapping结构修改为ES8的Mapping结构
 * 去除第三层的type
 */
public class JsonModifier {
    public static void main(String[] args) {
        // 获取当前文件夹下所有的 .json 文件
        File folder = new File("C:\\Users\\x\\Desktop\\截图\\2023-12-25备份ES数据\\m12");
        File[] files = folder.listFiles((dir, name) -> name.endsWith(".json")&&name.startsWith("m"));

        // 遍历每个文件
        for (File file : files) {
            try {
                // 读取文件内容
                Path path = Paths.get(file.getAbsolutePath());
                byte[] bytes = Files.readAllBytes(path);
                String content = new String(bytes);

                // 解析 JSON 数据
                Object jsonObject = JSON.parse(content, Feature.OrderedField);

                // 删除第三层的键
                deleteThirdLevelKeys(jsonObject, 1);

                // 将修改后的 JSON 写回原文件
                String jsonString = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat);
                Files.write(path, jsonString.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void deleteThirdLevelKeys(Object json, int level) {
        if (json instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) json;
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                if (value instanceof JSONObject) {
                    if (level == 2) {
                        JSONObject jsonObject2 = (JSONObject) value;
                        JSONObject tmp = (JSONObject)jsonObject2.get(jsonObject2.keySet().iterator().next());
                        jsonObject.put(key, tmp);
                    } else {
                        deleteThirdLevelKeys(value, level + 1);
                    }
                } else if (value instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) value;
                    for (int i = 0; i < jsonArray.size(); i++) {
                        deleteThirdLevelKeys(jsonArray.get(i), level);
                    }
                }
            }
        } else if (json instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) json;
            for (int i = 0; i < jsonArray.size(); i++) {
                deleteThirdLevelKeys(jsonArray.get(i), level);
            }
        }
    }
}