package com.yunhai.userbase.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.yunhai.platform.utils.exception.DException; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; /* * 杂项公用方法集合 * */ public class OtherUtil { /** * 十六进制转字符串 * @param hex * @return */ public final static String hexToString(String hex) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hex.length(); i += 2) { String hexSubstring = hex.substring(i, i + 2); int decimalValue = Integer.parseInt(hexSubstring, 16); sb.append((char) decimalValue); } return sb.toString(); } /** * @Description: 判断字符串能否序列化 * @Author: chenx * @Date: 2023/4/20 */ public final static boolean isJSONValid(String str) { try { JSONObject.parse(str); } catch (JSONException ex) { return false; } return true; } /** * @Description: 判断字符串能否序列化为json数组 * @Author: chenx * @Date: 2023/4/20 */ public final static boolean isJsonArray(String str) { if (!isJSONValid(str)) return false; try { Object object = JSON.parse(str); return object instanceof JSONArray; } catch (JSONException ex) { return false; } } /** * @Description: 数组深拷贝 * @Author: chenx * @Date: 2023/4/20 */ public final static List deepCopy(List src, Class clazz) { String jsonStr=JSON.toJSONString(src); if (!isJsonArray(jsonStr)) return src; return JSONArray.parseArray(jsonStr,clazz); } /** * @Description: 逗号分隔字符串转List数组 * @Author: chenx * @Date: 2023/4/20 */ public final static List SplitToList(String idsStr) { return Arrays.stream(idsStr.split(",")).map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList()); } /** * 判断是否为校领导 */ public final static Boolean isAdminById(Integer roleId){ return Arrays.asList(2,5,7).contains(roleId); } public static JSONObject getDataOrThrow(String result) { JSONObject root = JSON.parseObject(result); if (root.getIntValue("code") != 0) { throw new DException("接口异常: " + root.getString("msg")); } return root.getJSONObject("data"); } /** * result 里 data 直接就是数组 [],返回 List */ public static List getDataArray(String result) { JSONObject root = JSON.parseObject(result); if (root.getIntValue("code") != 0) { throw new DException("接口异常: " + root.getString("msg")); } // data 本身就是 JSONArray return root.getJSONArray("data").toJavaList(JSONObject.class); } /** * 根据 code 最大值返回学段 * 1~6 → 2 * 7~9 → 3 * 10~12→ 4 */ public static int calcStage(List codes) { if (codes == null || codes.isEmpty()) { throw new IllegalArgumentException("codes 不能为空"); } int max = codes.stream().max(Integer::compareTo).get(); if (max <= 6) return 2; if (max <= 9) return 3; return 4; } public static String getUUID(){ return UUID.randomUUID().toString().replace("-",""); } public static Integer parseIntNullable(Object val) { return val == null ? null : Integer.parseInt(val.toString()); } }