Java 压平Json


一、压平Json(包含JsonArray也压平)

public static void flattenJson(String prefix, Object json, Map<String, Object> flattenedMap) {
        if (json instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) json;
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                flattenJson(prefix + key + ".", value, flattenedMap);
            }
        } else if (json instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) json;
            for (int i = 0; i < jsonArray.size(); i++) {
                Object value = jsonArray.get(i);
                flattenJson(prefix + i + ".", value, flattenedMap);
            }
        } else {
            if (ObjectUtil.isEmpty(prefix)) {
                flattenedMap.put("row_data", json);
            } else {
                flattenedMap.put(prefix.substring(0, prefix.length() - 1), json);
            }
        }
    }

使用

public static void main(String[] args) {
        Map<String, Object> flattenedMap = new LinkedHashMap<>();
        String a = "{\"a\": 1,\"b\": \"b\",\"c\": {\"d\": 1},\"e\": [{\"f\": 1},\"1\",1,[{\"a\": 1}]]}";
        Object parse = JSON.parse(a);
        flattenJson("", parse, flattenedMap);
        System.out.println(flattenedMap);
    }

结果
Java 压平Json_第1张图片
所有层级的数据都解析出来了


二、压平Json(仅压平JsonObject)

private static void flattenJson(String prefix, JSONObject obj, Map<String, Object> flattenedMap) {
        for (String key : obj.keySet()) {
            Object value = obj.get(key);
            if (value instanceof JSONObject) {
                if (!flattenedMap.containsKey(key)) {
                    flattenedMap.put(key, value);
                }
                flattenJson(prefix + key + ".",(JSONObject) value,  flattenedMap);
            } else {
                flattenedMap.put(prefix + key, value);
            }
        }
    }

使用

public static void main(String[] args) {
        Map<String, Object> flattenedMap = new LinkedHashMap<>();
        String a = "{\"a\": 1,\"b\": \"b\",\"c\": {\"d\": 1},\"e\": [{\"f\": 1},\"1\",1,[{\"a\": 1}]]}";
        JSONObject parse = JSON.parseObject(a);
        flattenJson("", parse, flattenedMap);
        System.out.println(flattenedMap);
    }

结果
Java 压平Json_第2张图片
JsonArray的数据未解析

你可能感兴趣的:(Java,java,json,开发语言)