递归解析json任意层级文件
java工程的 resources
目录下 json/json_info_all.json 文件解析。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| import cn.hutool.core.io.resource.ClassPathResource; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.nacos.common.utils.CollectionUtils; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Map;
@Slf4j public class JsonConfig { private static final String JSON_FILE_PATH = "json/json_info_all.json"; private static final List<Map<String, Object>> DATA = Lists.newArrayList();
static { try { JSONArray jsonArray = JSON.parseObject(new ClassPathResource(JSON_FILE_PATH).getStream(), StandardCharsets.UTF_8, new TypeReference<JSONArray>() {{ }}.getType()); if (CollectionUtils.isNotEmpty(jsonArray)) { traverseChildren(jsonArray); } log.info("JSON层级解析完成!size={}", DATA.size()); } catch (Exception e) { log.error("JSON层级信息解析出错!", e); } }
private static void traverseChildren(JSONArray jsonArray) { Deque<JSONArray> stack = new LinkedList<>(); stack.push(jsonArray); while (!stack.isEmpty()) { JSONArray currentArray = stack.pop(); for (Object obj : currentArray) { if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; if (jsonObject.containsKey("children")) { JSONArray children = jsonObject.getJSONArray("children"); DATA.add(jsonObject); if (CollectionUtils.isNotEmpty(children)) { stack.push(children); } } } } } }
public static List<Map<String, Object>> getData() { return DATA; } }
|