Java實(shí)現(xiàn)駝峰與下劃線互轉(zhuǎn)的方法
1.使用 Guava 實(shí)現(xiàn)
先引入相關(guān)依賴
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency>
1.1 駝峰轉(zhuǎn)下劃線
public static void main(String[] args) { String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName"); System.out.println("轉(zhuǎn)換后結(jié)果是:"+resultStr); }
轉(zhuǎn)換后結(jié)果是:user_name
1.2 下劃線轉(zhuǎn)駝峰
public static void main(String[] args) { String resultStr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name"); System.out.println("轉(zhuǎn)換后結(jié)果是:"+resultStr); }
轉(zhuǎn)換后結(jié)果是:userName
2.自定義代碼轉(zhuǎn)
2.1駝峰轉(zhuǎn)下劃線
private static final Pattern TPATTERN = Pattern.compile("[A-Z0-9]"); private String teseDemo(String str) { Matcher matcher = TPATTERN.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); } matcher.appendTail(sb); return sb.toString(); }
2.2下劃線轉(zhuǎn)駝峰
private static final char UNICON = '_'; private String underlineToCamel(String param) { if (StringUtils.isBlank(param)) { return ""; } int len = param.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = Character.toLowerCase(param.charAt(i)); if (c == UNICON) { if (++i < len) { sb.append(Character.toUpperCase(param.charAt(i))); } } else { sb.append(c); } } return sb.toString(); }
2.3、另外兩種方法
/** * 下劃線轉(zhuǎn)駝峰 * @param str * @return */ public static String lineToHump(String str) { Pattern linePattern = Pattern.compile("_(\\w)"); 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(); } /** * 駝峰轉(zhuǎn)下劃線 * @param str * @return */ public static String humpToLine(String str) { Pattern humpPattern = Pattern.compile("[A-Z]"); 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(); }
2.4、工具類
public class Tool { private static Pattern linePattern = Pattern.compile("_(\\w)"); /** 下劃線轉(zhuǎn)駝峰 */ 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(); } /** 駝峰轉(zhuǎn)下劃線(簡(jiǎn)單寫法,效率低于{@link #humpToLine2(String)}) */ public static String humpToLine(String str) { return str.replaceAll("[A-Z]", "_$0").toLowerCase(); } private static Pattern humpPattern = Pattern.compile("[A-Z]"); /** 駝峰轉(zhuǎn)下劃線,效率比上面高 */ 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 } }
不糾結(jié)"“_”+matcher.group(0).toLowerCase()"的話,humpToLine2效率會(huì)比humpToLine高一些,看String#replaceAll方法源碼即可。
實(shí)體類:
import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User implements Serializable { /** * */ private static final long serialVersionUID = -329066647199569031L; private String userName; private String orderNo; }
工具類
import java.io.IOException; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; /** * JSON的駝峰和下劃線互轉(zhuǎn)幫助類 * * */ public class JsonUtils { /** * 將對(duì)象的大寫轉(zhuǎn)換為下劃線加小寫,例如:userName-->user_name * * @param object * @return * @throws JsonProcessingException */ public static String toUnderlineJSONString(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); mapper.setSerializationInclusion(Include.NON_NULL); String reqJson = mapper.writeValueAsString(object); return reqJson; } /** * 將下劃線轉(zhuǎn)換為駝峰的形式,例如:user_name-->userName * * @param json * @param clazz * @return * @throws IOException */ public static <T> T toSnakeObject(String json, Class<T> clazz) throws IOException{ ObjectMapper mapper = new ObjectMapper(); // mapper的configure方法可以設(shè)置多種配置(例如:多字段 少字段的處理) //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); T reqJson = mapper.readValue(json, clazz); return reqJson; } }
3.測(cè)試
import java.io.IOException; import org.junit.Test; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; public class JsonTest { @Test public void testToUnderlineJSONString(){ User user = new User("張三", "1111111"); try { String json = JsonUtils.toUnderlineJSONString(user); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } } @Test public void testToSnakeObject(){ String json = "{\"user_name\":\"張三\",\"order_no\":\"1111111\"}"; try { User user = JsonUtils.toSnakeObject(json, User.class); System.out.println(JSONObject.toJSONString(user)); } catch (IOException e) { e.printStackTrace(); } } }
測(cè)試結(jié)果:
{"user_name":"張三","order_no":"1111111"}
{"orderNo":"1111111","userName":"張三"}
以上就是Java實(shí)現(xiàn)駝峰與下劃線互轉(zhuǎn)的方法的詳細(xì)內(nèi)容,更多關(guān)于Java駝峰與下劃線互轉(zhuǎn)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Eclipse下使用ANT編譯提示OutOfMemory的解決方法
由于需要使用ANT編譯的代碼比較多,特別是在第一次變異的時(shí)候,會(huì)出現(xiàn)OutOfMemory錯(cuò)誤。并提示更改ANT_OPTS設(shè)定。2009-04-04不知道面試會(huì)不會(huì)問Lambda怎么用(推薦)
這篇文章主要介紹了Lambda表達(dá)式用法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04Java使用ant.jar執(zhí)行SQL腳本文件的示例代碼
這篇文章主要介紹了Java使用ant.jar執(zhí)行SQL腳本文件,文中通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-02-02Java8新特性Stream流中anyMatch和allMatch和noneMatch的區(qū)別解析
這篇文章主要介紹了Java8新特性Stream流中anyMatch和allMatch和noneMatch的區(qū)別解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-01-01Spring?容器初始化?register?與?refresh方法
這篇文章主要介紹了Spring?容器初始化?register?與?refresh方法,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07springboot學(xué)習(xí)之構(gòu)建簡(jiǎn)單項(xiàng)目搭建步驟詳解
這篇文章主要介紹了springboot學(xué)習(xí)之構(gòu)建簡(jiǎn)單項(xiàng)目搭建步驟詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10