将json字符串从外层到最内层依次连接,平铺成一个List<String>

2023-03-10 11:36:10 浏览数 (1)

就是将json平铺的功能,如

String jsonString = "{"a": {"b": {"c": 1}}, "d": [2, 3]}";

变成

[a.b.c=1, d[0]=2, d[1]=3]

这样能得到整个json的所有key,如果需要排重,可以用Set

代码语言:javascript复制
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class JSONUtils {

    public static List<String> flattenJson(String jsonString) {
        List<String> flattened = new ArrayList<>();
        flattenJson(JSON.parseObject(jsonString), "", flattened);
        return flattened;
    }

    private static void flattenJson(JSONObject obj, String prefix, List<String> flattened) {
        for (String key : obj.keySet()) {
            Object value = obj.get(key);
            String newPrefix = prefix   key;
            if (value instanceof JSONObject) {
                flattenJson((JSONObject) value, newPrefix   ".", flattened);
            } else if (value instanceof JSONArray) {
                JSONArray arr = (JSONArray) value;
                for (int i = 0; i < arr.size(); i  ) {
                    Object arrValue = arr.get(i);
                    if (arrValue instanceof JSONObject) {
                        flattenJson((JSONObject) arrValue, newPrefix   "["   i   "].", flattened);
                    } else {
                        flattened.add(newPrefix   "["   i   "]="   arrValue.toString()   "("   arrValue.getClass().getSimpleName()   ")");
                    }
                }
            } else {
                flattened.add(newPrefix   "="   value.toString()   "("   value.getClass().getSimpleName()   ")");
            }
        }
    }

}

0 人点赞