Utils

StringUtils

1
2
3
4
TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
.dateList(StringUtils.join(dateList,","))
.turnoverList(StringUtils.join(turnoverList,","))
.build();

能去掉列表的[ ],构造新的字符串,中间以,隔开

JSON.toJSONString()

fastjson

1
webSocketServer.sendToAllClient(JSON.toJSONString(map));

能把对象转换成 JSON 格式的字符串

BeanUtil.copyProperties

hutool

1
Employee employee = BeanUtil.copyProperties(employeeDTO, Employee.class);

JsonFormat

@DateTimeFormat和@JsonFormat都是处理时间格式化问题的!

image-20240904160907768

注意:

  1. 一旦使用yyyy-MM-dd 格式,如果传时分秒就会报错,或者是使用 yyyy-MM-dd HH:mm:ss,如果传yyyy-MM-dd 也会报错。
  2. 假如是springboot项目的话,使用这两个注解是不用导其他的依赖包的!
  3. 框架当中默认他会认为 前端传的是UTC时间,然后SpringMVC在接到参数的时候,会进行转换为本地区时间,向前端返回参数的时候会转换为UTC时间!
  4. 这两个注解可以选择在实体类的set方法当中使用,也可以在字段上使用,效果是一样的!

详细细节:@DateTimeFormat 和 @JsonFormat 注解详解-CSDN博客

@Data

​ 当使用@Data注解时,那么就会在此类中存在equals(Object other) 和 hashCode()方法,且不会使用父类的属性,这就导致了可能的问题。比如,有多个类有相同的部分属性,把它们定义到父类中,恰好id(数据库主键)也在父类中,那么就会存在部分对象在比较时,它们并不相等,却因为lombok自动生成的equals(Object other) 和 hashCode()方法判定为相等(不包括父属性的比较),从而导致出错。

​ 因此,有了@EqualsAndHashCode注解,@EqualsAndHashCode注解用于简化实体类子类的equals方法实现,callSuper属性控制是否考虑父类属性。当callSuper为true时,只有包括父类属性在内的所有属性都相等时,对象才被认为是相等的;若为false,则只比较当前类的属性。示例展示了不同callSuper设置下的equals方法行为差异。

修复此问题的方法很简单:

  1. 使用@Getter @Setter @ToString代替@Data并且自定义equals(Object other) 和 hashCode()方法,比如有些类只需要判断主键id是否相等即足矣。
  2. 或者使用在使用@Data时同时加上@EqualsAndHashCode(callSuper=true)注解。

pinyin4j

pinyin4j 是一个开源的流行java库,支持中文字符和拼音之间的转换,拼音输出格式可以定制使用来处理中文转换成拼音(汉语拼音,罗马拼音等),功能非常强大。

​ 很多时候我们都会需要把汉字转化成拼音,方便使用。例子:登录场景,客户提供的是一个中文名字,要做成登录,用中文名字来登录不太好,而且很容易造成乱码的情况出现。所以我们需要把中文登录名转成英文登录名。比如:“张三”需要装成“zhangsan”。

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
package com.ruoyi.system.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
* 中文转拼音工具类
*/
public class PinyinConverterUtil {


public static String toPinyin(String chineseText) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 设置为小写
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调

StringBuilder pinyinBuilder = new StringBuilder();

try {
for (char c : chineseText.toCharArray()) {
//将字符转为为字符串
if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) { // 判断是否为汉字
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
pinyinBuilder.append(pinyinArray[0]); // 取第一个拼音
} else {
pinyinBuilder.append(c); // 非汉字直接添加
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}

return pinyinBuilder.toString();
}
}