前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >将json字符串从外层到最内层依次连接,平铺成一个List<String>

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

作者头像
天涯泪小武
发布2023-03-10 11:36:10
8580
发布2023-03-10 11:36:10
举报
文章被收录于专栏:SpringCloud专栏SpringCloud专栏

就是将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() + ")");
            }
        }
    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-03-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档