/src/main/java/io/github/ljwlgl/fileutil/FastJsonUtil.java

https://github.com/LJWLgl/CommonUtil · Java · 491 lines · 349 code · 40 blank · 102 comment · 106 complexity · 0b046a3b18a8efe2b0504b6712d762bb MD5 · raw file

  1. package io.github.ljwlgl.fileutil;
  2. import com.alibaba.fastjson.*;
  3. import com.alibaba.fastjson.serializer.PropertyFilter;
  4. import org.apache.commons.collections.CollectionUtils;
  5. import org.apache.commons.lang3.StringUtils;
  6. import java.math.BigDecimal;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. import java.util.Objects;
  11. import java.util.stream.Collectors;
  12. public class FastJsonUtil {
  13. /**
  14. * 序列化Json
  15. */
  16. public static String toJsonString(Object object) {
  17. return JSON.toJSONString(object);
  18. }
  19. /**
  20. * 序列化Json,remove schema 属性
  21. *
  22. * @param object
  23. * @return
  24. */
  25. public static String toStringNoSchema(Object object) {
  26. return toJsonString(object, "schema");
  27. }
  28. /**
  29. * 序列化Json时删除不必要的属性
  30. *
  31. * @param object
  32. * @param reAttrs
  33. * @return String
  34. */
  35. public static String toJsonString(Object object, String... reAttrs) {
  36. List<String> reAttrList = Arrays.stream(reAttrs).filter(Objects::nonNull).collect(Collectors.toList());
  37. PropertyFilter filter = (obj, name, value) -> !reAttrList.contains(name);
  38. return JSON.toJSONString(object, filter);
  39. }
  40. public static String paramToString(Object object) {
  41. return toJsonString(object, "schema");
  42. }
  43. /**
  44. * 根据path向json加入指定对象
  45. * 注意:只支持JSONObject类型
  46. *
  47. * @param json 原json串
  48. * @param path 需要添加的路径
  49. * @param value 添加的对象
  50. * @return 新json串
  51. */
  52. public static String put(String json, String path, Object value) {
  53. if (StringUtils.isEmpty(path) || value == null) {
  54. return json;
  55. }
  56. String[] keys = null;
  57. if (path.contains(".")) {
  58. keys = path.split("\\.");
  59. } else {
  60. keys = new String[]{path};
  61. }
  62. JSONObject preObject = parseObject(json);
  63. JSONObject object = getJSONObjectByKeys(preObject, keys);
  64. if (object == null) {
  65. return json;
  66. }
  67. object.put(keys[keys.length - 1], value);
  68. return toJsonString(preObject);
  69. }
  70. /**
  71. * 根据path删除指定属性
  72. *
  73. * @param json 原json串
  74. * @param path 需要删除的json路径
  75. * @return 新的json串
  76. */
  77. public static String remove(String json, String path) {
  78. if (StringUtils.isEmpty(path)) {
  79. return json;
  80. }
  81. String[] keys = null;
  82. if (path.contains(".")) {
  83. keys = path.split("\\.");
  84. } else {
  85. keys = new String[]{path};
  86. }
  87. JSONObject preObject = parseObject(json);
  88. JSONObject object = getJSONObjectByKeys(preObject, keys);
  89. if (object == null) {
  90. return json;
  91. }
  92. object.remove(keys[keys.length - 1]);
  93. return toJsonString(preObject);
  94. }
  95. /**
  96. * 根据path替换指定属性, 只支持JSONObject
  97. *
  98. * @param json 原json串
  99. * @param path 需要替换的json路径
  100. * @return 新的json串
  101. */
  102. public static String replace(String json, String path, Object value) {
  103. if (StringUtils.isEmpty(path)) {
  104. return json;
  105. }
  106. String[] keys = null;
  107. if (path.contains(".")) {
  108. keys = path.split("\\.");
  109. } else {
  110. keys = new String[]{path};
  111. }
  112. JSONObject preObject = parseObject(json);
  113. JSONObject object = getJSONObjectByKeys(preObject, keys);
  114. if (object == null) {
  115. return json;
  116. }
  117. object.replace(keys[keys.length - 1], value);
  118. return toJsonString(preObject);
  119. }
  120. /**
  121. * 根据path替换指定属性, 支持JSONArray,但是不支持路径表达式
  122. *
  123. * @param json 原json串
  124. * @param path 需要替换的json路径
  125. * @return 新的json串
  126. */
  127. public static String replaceNew(String json, String path, String value) {
  128. if (StringUtils.isEmpty(path)) {
  129. return json;
  130. }
  131. String[] keys = null;
  132. if (path.contains(".")) {
  133. keys = path.split("\\.");
  134. } else {
  135. keys = new String[]{path};
  136. }
  137. List<JSONObject> res = new ArrayList<>();
  138. JSONObject preObject = parseObject(json);
  139. getJSONObjectByKeys(res, preObject, keys, 1);
  140. if (CollectionUtils.isEmpty(res)) {
  141. return json;
  142. }
  143. for (int j = 0; j < res.size(); j++) {
  144. Object oldValue = res.get(j).get(keys[keys.length - 1]);
  145. if (oldValue == null) {
  146. continue;
  147. }
  148. res.get(j).replace(keys[keys.length - 1], String.valueOf(value));
  149. }
  150. return toJsonString(preObject);
  151. }
  152. private static JSONObject getJSONObjectByKeys(JSONObject preObject, String[] keys) {
  153. JSONObject object = preObject;
  154. for (int i = keys[0].equals("$") ? 1 : 0; i < keys.length - 1; i++) {
  155. if (object != null) {
  156. object = object.getJSONObject(keys[i]);
  157. }
  158. }
  159. return object;
  160. }
  161. // 支持JSONArray
  162. private static void getJSONObjectByKeys(List<JSONObject> res, Object object, String[] keys, int index) {
  163. if (object == null || index >= keys.length) {
  164. return;
  165. }
  166. if (object instanceof JSONArray) {
  167. JSONArray array = (JSONArray) object;
  168. for (int i = 0; i < array.size(); i++) {
  169. getJSONObjectByKeys(res, array.get(i), keys, index);
  170. }
  171. return;
  172. } else if (object instanceof JSONObject) {
  173. JSONObject obj = (JSONObject) object;
  174. if (index < keys.length - 1) {
  175. getJSONObjectByKeys(res, obj.get(keys[index]), keys, index + 1);
  176. return;
  177. }
  178. res.add((JSONObject) object);
  179. }
  180. }
  181. public static JSONObject encryptJson(JSONObject jsonObject, List<String> paths) {
  182. if (jsonObject == null || CollectionUtils.isEmpty(paths)) {
  183. return jsonObject;
  184. }
  185. try {
  186. return encryptToObject(jsonObject, paths.toArray(new String[paths.size()]));
  187. } catch (Exception ex) {
  188. throw ex;
  189. }
  190. }
  191. public static String encryptJson(String json, List<String> paths) {
  192. if (StringUtils.isBlank(json) || CollectionUtils.isEmpty(paths)) {
  193. return json;
  194. }
  195. JSONObject preObject = parseObject(json);
  196. try {
  197. return encryptToJson(preObject, paths.toArray(new String[paths.size()]));
  198. } catch (Exception ex) {
  199. throw ex;
  200. }
  201. }
  202. /**
  203. * 加密json,支持JsonArray
  204. *
  205. * @param preObject 原json串
  206. * @param paths 需要加密的json路径
  207. * @return 新的json串
  208. */
  209. private static String encryptToJson(JSONObject preObject, String[] paths) {
  210. return toJsonString(encryptToObject(preObject, paths));
  211. }
  212. private static JSONObject encryptToObject(JSONObject preObject, String[] paths) {
  213. for (int i = 0; i < paths.length; i++) {
  214. if (StringUtils.isEmpty(paths[i])) {
  215. continue;
  216. }
  217. String[] keys = null;
  218. if (paths[i].contains(".")) {
  219. keys = paths[i].split("\\.");
  220. } else {
  221. keys = new String[]{paths[i]};
  222. }
  223. List<JSONObject> res = new ArrayList<>();
  224. getJSONObjectByKeys(res, preObject, keys, 1);
  225. if (CollectionUtils.isEmpty(res)) {
  226. continue;
  227. }
  228. for (int j = 0; j < res.size(); j++) {
  229. Object oldValue = res.get(j).get(keys[keys.length - 1]);
  230. if (oldValue == null) {
  231. continue;
  232. }
  233. res.get(j).replace(keys[keys.length - 1], encryptText(String.valueOf(oldValue)));
  234. }
  235. }
  236. return preObject;
  237. }
  238. private static String encryptText(String text) {
  239. if (StringUtils.isBlank(text)) {
  240. return text;
  241. }
  242. // 加密字符占字符比例的0.36
  243. int passLength = (int) Math.ceil(text.length() * 0.36);
  244. int midIdx = text.length() / 2;
  245. char[] arr = text.toCharArray();
  246. arr[midIdx] = '*';
  247. for (int i = 1, p = 1, k = 1; i < passLength; i++) {
  248. if (i % 2 == 0) {
  249. arr[midIdx + p] = '*';
  250. p++;
  251. } else {
  252. arr[midIdx - k] = '*';
  253. k++;
  254. }
  255. }
  256. return String.valueOf(arr);
  257. }
  258. /**
  259. * 根据path取出结果
  260. *
  261. * @param json
  262. * @param path
  263. * @return String
  264. */
  265. public static Object eval(String json, String path) {
  266. try {
  267. if (!json.contains("{") || !json.contains("}")) {
  268. return null;
  269. }
  270. JSONObject jsonObject = JSON.parseObject(json);
  271. return JSONPath.eval(jsonObject, path);
  272. } catch (Exception ex) {
  273. return null;
  274. }
  275. }
  276. public static Object eval(JSONObject jsonObject, String path) {
  277. try {
  278. return JSONPath.eval(jsonObject, path);
  279. } catch (Exception ex) {
  280. return null;
  281. }
  282. }
  283. /**
  284. * 根据path从json中取出结果并反序列成JavaBean
  285. *
  286. * @param json json字符串
  287. * @param path 需要的json路径
  288. * @param clz class
  289. * @param <T> 具体类型
  290. * @return res
  291. */
  292. @SuppressWarnings("unchecked")
  293. public static <T> T eval(String json, String path, Class<T> clz) {
  294. Object obj = eval(json, path);
  295. if (obj == null) {
  296. return null;
  297. }
  298. return instanceOf(obj, clz);
  299. }
  300. public static <T> T eval(JSONObject jsonObject, String path, Class<T> clz) {
  301. Object obj = eval(jsonObject, path);
  302. if (obj == null) {
  303. return null;
  304. }
  305. return instanceOf(obj, clz);
  306. }
  307. private static <T> T instanceOf(Object obj, Class<T> clz) {
  308. if (obj instanceof String) {
  309. return valueOf(obj, clz);
  310. } else if (obj instanceof Integer) {
  311. return valueOf(obj, clz);
  312. } else if (obj instanceof Long) {
  313. return valueOf(obj, clz);
  314. } else if (obj instanceof BigDecimal) {
  315. return valueOf(obj, clz);
  316. } else if (obj instanceof JSONObject) {
  317. return JSONObject.parseObject(JSON.toJSONString(obj), clz);
  318. } else if (obj instanceof JSONArray) {
  319. return valueOf(obj, clz);
  320. } else {
  321. return null;
  322. }
  323. }
  324. private static <T> T valueOf(Object obj, Class<T> clz) {
  325. if (clz.equals(Long.class)) {
  326. return (T) Long.valueOf(obj.toString());
  327. } else if (clz.equals(Integer.class)) {
  328. return (T) Integer.valueOf(obj.toString());
  329. } else if (clz.equals(String.class)) {
  330. return (T) obj.toString();
  331. } else if (clz.equals(Boolean.class)) {
  332. return (T) Boolean.valueOf(obj.toString());
  333. } else if (clz.equals(Double.class)) {
  334. return (T) Double.valueOf(obj.toString());
  335. } else if (clz.equals(Float.class)) {
  336. return (T) Float.valueOf(obj.toString());
  337. } else if (clz.equals(BigDecimal.class)) {
  338. return (T) BigDecimal.valueOf(Double.valueOf(obj.toString()));
  339. } else {
  340. return null;
  341. }
  342. }
  343. /**
  344. * 根据path从json中取出结果并反序列成JavaBean,该方法只支持array
  345. *
  346. * @param json json字符串
  347. * @param path 需要的json路径
  348. * @param clz class
  349. * @param <T> 具体类型
  350. * @return res
  351. */
  352. public static <T> List<T> evals(String json, String path, Class<T> clz) {
  353. Object obj = eval(json, path);
  354. if (obj == null) {
  355. return null;
  356. }
  357. if (obj instanceof JSONArray) {
  358. return JSONArray.parseArray(JSON.toJSONString(obj), clz);
  359. }
  360. return null;
  361. }
  362. /**
  363. * 反序列化Json
  364. */
  365. public static <T> T parseObject(String json, Class<T> clazz) {
  366. return JSON.parseObject(json, clazz);
  367. }
  368. public static JSONObject parseObject(String json) {
  369. return JSON.parseObject(json);
  370. }
  371. public static Object parse(String text) {
  372. return JSON.parse(text);
  373. }
  374. /**
  375. * 反序列化成List
  376. */
  377. public static <T> List<T> parseArray(String json, Class<T> clazz) {
  378. return JSON.parseArray(json, clazz);
  379. }
  380. /**
  381. * 获取Json字符串某节点的值
  382. */
  383. public static String getJsonValue(String jsonStr, String key) {
  384. if (StringUtils.isEmpty(jsonStr) || StringUtils.isEmpty(key)) {
  385. return null;
  386. }
  387. JSONObject object = JSONObject.parseObject(jsonStr);
  388. return object.getString(key);
  389. }
  390. public static boolean containsKey(String jsonStr, String key) {
  391. boolean result = false;
  392. if (StringUtils.isEmpty(jsonStr) || StringUtils.isEmpty(key)) {
  393. return result;
  394. }
  395. try {
  396. JSONObject object = JSONObject.parseObject(jsonStr);
  397. result = object.containsKey(key);
  398. } catch (Exception ex) {
  399. result = false;
  400. }
  401. return result;
  402. }
  403. /**
  404. * 判断Json是否包含keys属性
  405. *
  406. * @param jsonStr json
  407. * @param keys 属性的可变长参数
  408. * @return boolean
  409. */
  410. public static boolean containsKey(String jsonStr, String... keys) {
  411. if (StringUtils.isEmpty(jsonStr) || keys == null || keys.length == 0) {
  412. return false;
  413. }
  414. JSONObject object = JSONObject.parseObject(jsonStr);
  415. return containsKey(object, keys);
  416. }
  417. public static boolean containsKey(JSONObject jsonObject, String... keys) {
  418. if (jsonObject == null || keys == null || keys.length == 0) {
  419. return false;
  420. }
  421. try {
  422. for (int i = 0; i < keys.length; i++) {
  423. if (!jsonObject.containsKey(keys[i])) {
  424. return false;
  425. }
  426. }
  427. } catch (Exception ex) {
  428. return false;
  429. }
  430. return true;
  431. }
  432. /**
  433. * 判断是否是Json串
  434. *
  435. * @param str 检测字符串
  436. * @return bool
  437. */
  438. public static boolean isJSON(String str) {
  439. if (StringUtils.isBlank(str)) {
  440. return false;
  441. }
  442. boolean result;
  443. try {
  444. JSON.parse(str);
  445. result = true;
  446. } catch (JSONException e) {
  447. result = false;
  448. }
  449. return result;
  450. }
  451. }