Jeecgboot 字典值自动转化:DictAspect类方法改造,支持IPage、List、Objec ...

打印 上一主题 下一主题

主题 506|帖子 506|积分 1518

改造的是DictAspect类:
原来使用的 parseDictText(Object result)方法,针对返回对象为Result 的IPage的分页列表数据进举措态字典注入,当单个对象查询,列表查询,大概多个数据放到Map中时,就不会自动转化,在web端进行展示的时候就需要连表查询大概手动查询字典值,不方便使用。
于是我改造了parseDictText()方法,不仅针对返回对象为Result时的分页列表,还支持列表、对象以及Map范例的结果。实在Result对象执行setResult()方式时进行自动注入转换。
原方法

代码:
  1. private Object parseDictText(Object result) {
  2.         //if (result instanceof Result) {
  3.         if (true) {
  4.             if (((Result) result).getResult() instanceof IPage) {
  5.                 List<JSONObject> items = new ArrayList<>();
  6.                 //step.1 筛选出加了 Dict 注解的字段列表
  7.                 List<Field> dictFieldList = new ArrayList<>();
  8.                 // 字典数据列表, key = 字典code,value=数据列表
  9.                 Map<String, List<String>> dataListMap = new HashMap<>(5);
  10.                 //取出结果集
  11.                 List<Object> records=((IPage) ((Result) result).getResult()).getRecords();
  12.                 //update-begin--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  13.                 Boolean hasDict= checkHasDict(records);
  14.                 if(!hasDict){
  15.                     return result;
  16.                 }
  17.                 log.debug(" __ 进入字典翻译切面 DictAspect —— " );
  18.                 //update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  19.                 for (Object record : records) {
  20.                     String json="{}";
  21.                     try {
  22.                         //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  23.                         //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  24.                          json = objectMapper.writeValueAsString(record);
  25.                         //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  26.                     } catch (JsonProcessingException e) {
  27.                         log.error("json解析失败"+e.getMessage(),e);
  28.                     }
  29.                     //update-begin--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  30.                     JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
  31.                     //update-end--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  32.                     //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  33.                     //for (Field field : record.getClass().getDeclaredFields()) {
  34.                     // 遍历所有字段,把字典Code取出来,放到 map 里
  35.                     for (Field field : oConvertUtils.getAllFields(record)) {
  36.                         String value = item.getString(field.getName());
  37.                         if (oConvertUtils.isEmpty(value)) {
  38.                             continue;
  39.                         }
  40.                     //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  41.                         if (field.getAnnotation(Dict.class) != null) {
  42.                             if (!dictFieldList.contains(field)) {
  43.                                 dictFieldList.add(field);
  44.                             }
  45.                             String code = field.getAnnotation(Dict.class).dicCode();
  46.                             String text = field.getAnnotation(Dict.class).dicText();
  47.                             String table = field.getAnnotation(Dict.class).dictTable();
  48.                             //update-begin---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  49.                             String dataSource = field.getAnnotation(Dict.class).ds();
  50.                             //update-end---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  51.                             List<String> dataList;
  52.                             String dictCode = code;
  53.                             if (!StringUtils.isEmpty(table)) {
  54.                                 //update-begin---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  55.                                 dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  56.                                 //update-end---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  57.                             }
  58.                             dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
  59.                             this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
  60.                         }
  61.                         //date类型默认转换string格式化日期
  62.                         //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  63.                         //if (JAVA_UTIL_DATE.equals(field.getType().getName())&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
  64.                             //SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  65.                             // item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  66.                         //}
  67.                         //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  68.                     }
  69.                     items.add(item);
  70.                 }
  71.                 //step.2 调用翻译方法,一次性翻译
  72.                 Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
  73.                 //step.3 将翻译结果填充到返回结果里
  74.                 for (JSONObject record : items) {
  75.                     for (Field field : dictFieldList) {
  76.                         String code = field.getAnnotation(Dict.class).dicCode();
  77.                         String text = field.getAnnotation(Dict.class).dicText();
  78.                         String table = field.getAnnotation(Dict.class).dictTable();
  79.                         //update-begin---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  80.                         // 自定义的字典表数据源
  81.                         String dataSource = field.getAnnotation(Dict.class).ds();
  82.                         //update-end---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  83.                         String fieldDictCode = code;
  84.                         if (!StringUtils.isEmpty(table)) {
  85.                             //update-begin---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  86.                             fieldDictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  87.                             //update-end---author:chenrui ---date:20231221  for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  88.                         }
  89.                         String value = record.getString(field.getName());
  90.                         if (oConvertUtils.isNotEmpty(value)) {
  91.                             List<DictModel> dictModels = translText.get(fieldDictCode);
  92.                             if(dictModels==null || dictModels.size()==0){
  93.                                 continue;
  94.                             }
  95.                             String textValue = this.translDictText(dictModels, value);
  96.                             log.debug(" 字典Val : " + textValue);
  97.                             log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  98.                             // TODO-sun 测试输出,待删
  99.                             log.debug(" ---- dictCode: " + fieldDictCode);
  100.                             log.debug(" ---- value: " + value);
  101.                             log.debug(" ----- text: " + textValue);
  102.                             log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));
  103.                             record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  104.                         }
  105.                     }
  106.                 }
  107.                 ((IPage) ((Result) result).getResult()).setRecords(items);
  108.             }
  109.         }
  110.         return result;
  111.     }
复制代码
改造

判断通报参数的范例,是IPage、List、Map、Object,如果是IPage、List、Map,则把对象中的数据拿出来再挨个转换,改造为新的结果数据返回。
  1.   private Object parseDictText(Object result) {
  2.         if (result instanceof Result) {
  3.             List<Object> list = new LinkedList<>();
  4.             if (((Result) result).getResult() instanceof IPage) {
  5.                 //分页
  6.                 list = ((IPage) ((Result) result).getResult()).getRecords();
  7.             } else if (((Result) result).getResult() instanceof List) {
  8.                 //List集合
  9.                 list = (List<Object>) ((Result) result).getResult();
  10.             } else if (((Result) result).getResult() instanceof Map) {
  11.                 //map
  12.                 Map<Object, Object> map = (Map<Object, Object>) ((Result) result).getResult();
  13.                 Map<Object, Object> itemMap = new HashMap<>();
  14.                 for (Map.Entry entry : map.entrySet()) {
  15.                     //System.out.println(entry.getKey() + " " + entry.getValue());
  16.                     Map mapRe = new HashMap();
  17.                     if (entry.getValue() instanceof List) {
  18.                         //列表
  19.                         List<Object> listItems = new ArrayList<>();
  20.                         for (Object record : (List) entry.getValue()) {
  21.                             if (checkIsJsonStr(record)) {
  22.                                 //字典翻译
  23.                                 record = this.dictEscape(record);
  24.                             }
  25.                             listItems.add(record);
  26.                         }
  27.                         itemMap.put(entry.getKey(), listItems);
  28.                     } else if (entry.getValue() instanceof Object) {
  29.                         //单对象
  30.                         Object record = entry.getValue();
  31.                         //判断能否转换成JSON,因为有些结果集返回的是String类型,导致翻译异常,因此判断是否可以转换json
  32.                         if (checkIsJsonStr(record)) {
  33.                             //字典翻译
  34.                             record = this.dictEscape(record);
  35.                         }
  36.                         itemMap.put(entry.getKey(), record);
  37.                     }
  38.                 }
  39.                 ((Result) result).setResult(itemMap);
  40.             } else {
  41.                 //单对象
  42.                 Object record = ((Result) result).getResult();
  43.                 //判断能否转换成JSON,因为有些结果集返回的是String类型,导致翻译异常,因此判断是否可以转换json
  44.                 if (checkIsJsonStr(record)) {
  45.                     //字典翻译
  46.                     record = this.dictEscape(record);
  47.                 }
  48.                 ((Result) result).setResult(record);
  49.             }
  50.             //列表解析
  51.             if (list != null && list.size() > 0) {
  52.                 List<Object> items = new ArrayList<>();
  53.                 for (Object record : list) {
  54.                     if (checkIsJsonStr(record)) {
  55.                         //字典翻译
  56.                         record = this.dictEscape(record);
  57.                     }
  58.                     items.add(record);
  59.                 }
  60.                 if (((Result) result).getResult() instanceof IPage) {
  61.                     ((IPage) ((Result) result).getResult()).setRecords(items);
  62.                 } else if (((Result) result).getResult() instanceof List) {
  63.                     ((Result) result).setResult(items);
  64.                 }
  65.             }
  66.         }
  67.         return result;
  68.     }
复制代码
字典翻译方法:
  1.     /**
  2.      * 字典翻译
  3.      *
  4.      * @param record
  5.      * @return
  6.      */
  7.     private JSONObject dictEscape(Object record) {
  8.         ObjectMapper mapper = new ObjectMapper();
  9.         String json = "{}";
  10.         JSONObject item = null;
  11.         try {
  12.             //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  13.             json = mapper.writeValueAsString(record);//对象序列化为JSON字符串
  14.         } catch (JsonProcessingException e) {
  15.             log.error("json解析失败" + e.getMessage(), e);
  16.         }
  17.         try {
  18.             item = JSONObject.parseObject(json);
  19.             //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  20.             for (Field field : oConvertUtils.getAllFields(record)) {
  21.                 //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  22.                 if (field.getAnnotation(Dict.class) != null) {
  23.                     String code = field.getAnnotation(Dict.class).dicCode();
  24.                     String text = field.getAnnotation(Dict.class).dicText();
  25.                     String table = field.getAnnotation(Dict.class).dictTable();
  26.                     String key = String.valueOf(item.get(field.getName()));
  27.                     //翻译字典值对应的txt
  28.                     String textValue = key;
  29.                     //非中文时翻译
  30.                     if (!checkCountName(key)) {
  31.                         textValue = translateDictValue(code, text, table, key);
  32.                     }
  33.                     log.debug(" 字典Val : " + textValue);
  34.                     log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  35.                     item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  36.                 }
  37.                 //date类型默认转换string格式化日期
  38.                 if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
  39.                     SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  40.                     item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  41.                 }
  42.             }
  43.         } catch (Exception e) {
  44.             log.info("字典翻译异常:" + e.getMessage(), e);
  45.         }
  46.         return item;
  47.     }
复制代码
检测是否是中文:
  1. /**
  2.      * 检测是否是中文
  3.      *
  4.      * @param countName
  5.      * @return
  6.      */
  7.     public static boolean checkCountName(String countName) {
  8.         Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
  9.         Matcher m = p.matcher(countName);
  10.         if (m.find()) {
  11.             return true;
  12.         }
  13.         return false;
  14.     }
复制代码
检测是否可转换为JSON字符串
  1. /**
  2.      * 检测是否可转换为JSON字符串
  3.      *
  4.      * @param record
  5.      * @return
  6.      */
  7.     public static boolean checkIsJsonStr(Object record) {
  8.         boolean jsonFlag = false;
  9.         try {
  10.             String json = new ObjectMapper().writeValueAsString(record);
  11.             if (json.startsWith("{")) {
  12.                 jsonFlag = true;
  13.             }
  14.         } catch (JsonProcessingException e) {
  15.             e.printStackTrace();
  16.         }
  17.         return jsonFlag;
  18.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

灌篮少年

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表