前言
在java开发中,平常可能会经常接触到驼峰转下划线、下划线转驼峰的操作,在平常的项目中,我们可以写一个全局的工具类,防止重复码🧱的操作,不多说直接上代码
驼峰下划线互转
本次用google的gson包
import com.google.gson.*;
public class CamelAndUnderlineUtil {
private CamelAndUnderlineUtil() {
throw new IllegalStateException("CamelAndUnderlineUtil.Class");
}
/**
* yyyy-MM-dd HH:mm格式
*/
private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy-MM-dd 格式
*/
private static final String YYYY_MM_DD = "yyyy-MM-dd";
/**
* 序列化
*/
private static JsonSerializer<LocalDateTime> jsonSerializerDateTime = (localDateTime, type, jsonSerializationContext)
-> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS)));
private static JsonSerializer<LocalDate> jsonSerializerDate = (localDate, type, jsonSerializationContext)
-> new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern(YYYY_MM_DD)));
/**
* 反序列化
*/
private static JsonDeserializer<LocalDateTime> jsonDeserializerDateTime = (jsonElement, type, jsonDeserializationContext)
-> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
private static JsonDeserializer<LocalDate> jsonDeserializerDate = (jsonElement, type, jsonDeserializationContext)
-> LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern(YYYY_MM_DD));
private static Gson gson;
static {
gson = new GsonBuilder()
//设置驼峰蛇形互转
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
//设置空值不忽略
.serializeNulls()
//设置时间格式化
.setDateFormat(YYYY_MM_DD_HH_MM_SS)
//gson注册序列化适配器
.registerTypeAdapter(LocalDateTime.class, jsonSerializerDateTime)
.registerTypeAdapter(LocalDate.class, jsonSerializerDate)
//gson注册反序列化适配器
.registerTypeAdapter(LocalDateTime.class, jsonDeserializerDateTime)
.registerTypeAdapter(LocalDate.class, jsonDeserializerDate)
.create();
}
/**
* 驼峰转下划线
*
* @param object 传入的对象(字段都是驼峰命名)
* @return java.lang.String 返回的对象(json形式)
* @author Songsong
*/
public static String camelToUnderline(Object object) {
return gson.toJson(object);
}
/**
* 下划线转驼峰
*
* @param source 传入的json(字段都是下划线)
* @param clazz 返回的对象(字段都是驼峰命名)
* @return T
* @author Songsong
*/
public static <T> T underlineToCamel(String source, Class<T> clazz) {
return gson.fromJson(source, clazz);
}
总结
有需要用到的地方直接引用该工具类,或者添加一个@Component变成一个spring bean,需要引用的地方直接注入使用即可,这样做的好处之一就是因为Gson是在静态代码块构建的,只会被执行一次