项目中配置的字段映射方式都是驼峰映射,有些时候需要导出json数据,需要将驼峰映射后的数据转换成下划线方式的
经过多方查找,最后看到jackjson中objectMapper配置类PropertyNamingStrategy可以直接实现各种类型的转换,什么下划线转驼峰、驼峰转下滑应有尽有
// 下划线
public static final PropertyNamingStrategy SNAKE_CASE = new PropertyNamingStrategy.SnakeCaseStrategy();
// 大驼峰
public static final PropertyNamingStrategy UPPER_CAMEL_CASE = new PropertyNamingStrategy.UpperCamelCaseStrategy();
// 小驼峰
public static final PropertyNamingStrategy LOWER_CAMEL_CASE = new PropertyNamingStrategy();
// ......
public static final PropertyNamingStrategy LOWER_CASE = new PropertyNamingStrategy.LowerCaseStrategy();
public static final PropertyNamingStrategy KEBAB_CASE = new PropertyNamingStrategy.KebabCaseStrategy();
下面直接展示转换代码:
/**
* 驼峰映射的对象转换成下划线形式的对象
* @param map
* @param <T>
* @return
*/
public static <T> Map<String, T> objectToMap(Map<String,T> map){
Map<String, T> resultMap = new HashMap<>();
PropertyNamingStrategy SNAKE_CASE = PropertyNamingStrategy.SNAKE_CASE;
for(Map.Entry<String,T> entry : map.entrySet()){
resultMap.put(((PropertyNamingStrategy.SnakeCaseStrategy) SNAKE_CASE).translate(entry.getKey()),entry.getValue());
}
return resultMap;
}
需要转换什么类型可以自行选择,只需要替换上边代码即可,测试代码:
public static void main(String[] args) {
try {
Map map=new HashMap();
map.put("xmName","测试");
map.put("nameAuthor","simple");
Map<String, Object> map1 = objectToMap(map);
System.out.println(map1);
} catch (Exception e) {
e.printStackTrace();
System.out.println("转换失败");
}
}
转换结果如下: