博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java下划线与驼峰命名互转
阅读量:7082 次
发布时间:2019-06-28

本文共 4396 字,大约阅读时间需要 14 分钟。

方式一:

下划线与驼峰命名转换:

 
public class Tool {
private static Pattern linePattern = Pattern.compile("_(\\w)");
/** 下划线转驼峰 */
public static String lineToHump(String str) {
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/** 驼峰转下划线(简单写法,效率低于{
@link #humpToLine2(String)}) */
public static String humpToLine(String str) {
return str.replaceAll("[A-Z]", "_$0").toLowerCase();
}
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/** 驼峰转下划线,效率比上面高 */
public static String humpToLine2(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String lineToHump = lineToHump("f_parent_no_leader");
System.out.println(lineToHump);// fParentNoLeader
System.out.println(humpToLine(lineToHump));// f_parent_no_leader
System.out.println(humpToLine2(lineToHump));// f_parent_no_leader
}
}

不纠结""_"+matcher.group(0).toLowerCase()"的话,humpToLine2效率会比humpToLine高一些,看String#replaceAll方法源码即可。

方式二:

实体类:

1 import java.io.Serializable; 2 import lombok.AllArgsConstructor; 3 import lombok.Data; 4 import lombok.NoArgsConstructor; 5  6 @Data 7 @AllArgsConstructor 8 @NoArgsConstructor 9 public class User implements Serializable {10     /**11      * 12      */13     private static final long serialVersionUID = -329066647199569031L;14     15     private String userName;16     17     private String orderNo;18 }

帮助类:

1 import java.io.IOException; 2  3 import com.fasterxml.jackson.annotation.JsonInclude.Include; 4 import com.fasterxml.jackson.core.JsonProcessingException; 5 import com.fasterxml.jackson.databind.ObjectMapper; 6 import com.fasterxml.jackson.databind.PropertyNamingStrategy; 7  8 /** 9  * JSON的驼峰和下划线互转帮助类10  * 11  * @author yangzhilong12  *13  */14 public class JsonUtils {15 16     /**17      * 将对象的大写转换为下划线加小写,例如:userName-->user_name18      * 19      * @param object20      * @return21      * @throws JsonProcessingException22      */23     public static String toUnderlineJSONString(Object object) throws JsonProcessingException{24         ObjectMapper mapper = new ObjectMapper();25         mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);26         mapper.setSerializationInclusion(Include.NON_NULL);      27         String reqJson = mapper.writeValueAsString(object);28         return reqJson;29     }30 31     /**32      * 将下划线转换为驼峰的形式,例如:user_name-->userName33      * 34      * @param json35      * @param clazz36      * @return37      * @throws IOException38      */39     public static 
T toSnakeObject(String json, Class
clazz) throws IOException{40 ObjectMapper mapper = new ObjectMapper();    // mapper的configure方法可以设置多种配置(例如:多字段 少字段的处理)        //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 41 mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);42 T reqJson = mapper.readValue(json, clazz);43 return reqJson;44 }45 }

单元测试类:

1 import java.io.IOException; 2  3 import org.junit.Test; 4  5 import com.alibaba.fastjson.JSONObject; 6 import com.fasterxml.jackson.core.JsonProcessingException; 7  8 public class JsonTest { 9     10     @Test11     public void testToUnderlineJSONString(){12         User user = new User("张三", "1111111");13         try {14             String json = JsonUtils.toUnderlineJSONString(user);15             System.out.println(json);16         } catch (JsonProcessingException e) {17             e.printStackTrace();18         }19     }20     21     @Test22     public void testToSnakeObject(){23         String json = "{\"user_name\":\"张三\",\"order_no\":\"1111111\"}";24         try {25             User user = JsonUtils.toSnakeObject(json, User.class);26             System.out.println(JSONObject.toJSONString(user));27         } catch (IOException e) {28             e.printStackTrace();29         }30     }31 }

测试结果:

1 {"user_name":"张三","order_no":"1111111"}2 3 {"orderNo":"1111111","userName":"张三"}

 

分类: ,
+加关注
1
0
上一篇:
下一篇:

转载于:https://www.cnblogs.com/zhuhui-site/p/10090880.html

你可能感兴趣的文章
GDAL的安装和配置(编译proj.4)
查看>>
Swagger2使用记录
查看>>
目标主体名称不正确,无法生成 SSPI 上下文
查看>>
使用jquery获取url参数
查看>>
asp.net 获取网站根目录
查看>>
小程序animation动画效果综合应用案例(交流QQ群:604788754)
查看>>
网站头信息的区别所在:
查看>>
web.py实现jsonp
查看>>
zabbix server3.4 使用mailx配置邮件报警
查看>>
nodejs cluster 学习记录
查看>>
基层管理之四:创业之路的一点思考
查看>>
python assert的作用
查看>>
【转】8.caffe:make_mean.sh( 数据平均化 )
查看>>
Location of several networks in brain
查看>>
constexpr函数"QAlgorithmsPrivate::qt_builtin_popcount"不会生成常数表达式
查看>>
C++中struct 和 class的区别
查看>>
第二个冲刺周期day5
查看>>
JS动态绑定数据 一行多列算法
查看>>
浅析Linux服务器集群系统技术
查看>>
python操作redis用法详解
查看>>