写在前面
一、下划线 <----> 驼峰
1.1、hutool 代码示例
@Test
public void t2() {
Map<String, Object> a = new HashMap<String, Object>() {
{
put("area_id", 100);
put("area_Name", null);
}};
Map<String, Object> b = new HashMap<>();
a.forEach((k,v) -> b.put(StrUtil.toCamelCase(k), v));
System.out.println(b);
}
// 结果
// {areaId=100, areaName=null}
@Test
public void t21() {
Map<String, Object> a = new HashMap<String, Object>() {
{
put("areaId", 100);
put("areaName", null);
}};
Map<String, Object> b = new HashMap<>();
a.forEach((k,v) -> b.put(StrUtil.toUnderlineCase(k), v));
System.out.println(b);
}
// {area_name=null, area_id=100}
1.2、Guava
@Test
public void t3() {
Map<String, Object> a = new HashMap<String, Object>() {
{
put("area_id", 100);
put("area_Name", null);
}};
Map<String, Object> b = new HashMap<>();
a.forEach((k,v) -> b.put(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, k), v));
System.out.println(b);
}
// {areaId=100, areaName=null}
@Test
public void t31() {
Map<String, Object> a = new HashMap<String, Object>() {
{
put("areaId", 100);
put("areaName", null);
}};
Map<String, Object> b = new HashMap<>();
a.forEach((k,v) -> b.put(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, k), v));
System.out.println(b);
}
//
// {area_name=null, area_id=100}
1.3、Gson + Hutool/Guava
这里其实Gson 并没具体实现下划线和 驼峰式的互转,只提供了 驼峰式 到 空格,下划线、中横线、首字母大写的单项转换,
从其他任何到驼峰式是没有实现的,不过Gson 提供了很方便的自定义转换策略,如下,
下面代码,Gson + Hutool 的实现下划线转驼峰命名 ,关于Gson 的相关操作学习,可参考,这里
@Test
public void t19() {
FieldNamingStrategy customPolicy = new FieldNamingStrategy() {
@Override
public String translateName(Field f) {
return StrUtil.toCamelCase(f.getName());
}
};
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingStrategy(customPolicy);
Gson gson = gsonBuilder.create();
UserNaming user = new UserNaming("Norman", "norman@futurestud.io", true, 26);
String usersJson = gson.toJson(user);
System.out.println(usersJson);
}
对于其它形式的互转,除了Gson本身实现的几个,另外别的都是可以自定义实现转换规则的,这里就不再详细介绍说明了…