package com.example.server.utils; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import org.apache.commons.lang3.ArrayUtils; public class JsonUtils2 { public static boolean setArrJsonValueByPath(JSONObject pJSONObject, String[] path, String searchKey, String searchValue, String targetKey, Object value) { if (path.length == 1) { JSONArray jsonArray = pJSONObject.getJSONArray(path[0]); for (int i = 0; i < jsonArray.size(); i++ ) { JSONObject jsonObject = jsonArray.getJSONObject(i); if (jsonObject.get(searchKey).equals(searchValue)) { jsonObject.put(targetKey, value); } } return true; } else { JSONObject sJSONObject = pJSONObject.getJSONObject(path[0]); path = ArrayUtils.remove(path, 0); setArrJsonValueByPath(sJSONObject, path, searchKey, searchValue, targetKey, value); } return false; } public static Object getArrJsonValueByPath(JSONObject pJSONObject, String[] path, String searchKey, String searchValue, String targetKey) { if (path.length == 1) { JSONArray jsonArray = pJSONObject.getJSONArray(path[0]); for (int i = 0; i < jsonArray.size(); i++ ) { JSONObject jsonObject = jsonArray.getJSONObject(i); if (jsonObject.get(searchKey).equals(searchValue)) { return jsonObject.get(targetKey); } } return null; } else { JSONObject sJSONObject = pJSONObject.getJSONObject(path[0]); path = ArrayUtils.remove(path, 0); return getArrJsonValueByPath(sJSONObject, path, searchKey, searchValue, targetKey); } } public static boolean setJsonValueByPath(JSONObject pJSONObject, String[] path, Object value) { if (path.length == 1) { pJSONObject.put(path[0], value); return true; } else { JSONObject sJSONObject = pJSONObject.getJSONObject(path[0]); if (sJSONObject==null){ sJSONObject = new JSONObject("{}"); pJSONObject.put(path[0],sJSONObject); } path = ArrayUtils.remove(path, 0); setJsonValueByPath(sJSONObject, path, value); } return false; } public static Object getJsonValueByPath(JSONObject pJSONObject, String[] path) { if (path.length == 1) { return pJSONObject.get(path[0]); } else { JSONObject sJSONObject = pJSONObject.getJSONObject(path[0]); if (sJSONObject==null) return null; path = ArrayUtils.remove(path, 0); return getJsonValueByPath(sJSONObject, path); } } }