1. 程式人生 > >java下劃線與駝峰命名互轉

java下劃線與駝峰命名互轉

方式一:

下劃線與駝峰命名轉換:


   
  1. public class Tool {
  2. private static Pattern linePattern = Pattern.compile( "_(\\w)");
  3. /** 下劃線轉駝峰 */
  4. public static String lineToHump(String str) {
  5. str = str.toLowerCase();
  6. Matcher matcher = linePattern.matcher(str);
  7. StringBuffer sb = new StringBuffer();
  8. while (matcher.find()) {
  9. matcher.appendReplacement(sb, matcher.group( 1
    ).toUpperCase());
  10. }
  11. matcher.appendTail(sb);
  12. return sb.toString();
  13. }
  14. /** 駝峰轉下劃線(簡單寫法,效率低於{@link #humpToLine2(String)}) */
  15. public static String humpToLine(String str) {
  16. return str.replaceAll( "[A-Z]", "_$0").toLowerCase();
  17. }
  18. private static Pattern humpPattern = Pattern.compile( "[A-Z]");
  19. /** 駝峰轉下劃線,效率比上面高 */
  20. public static String humpToLine2(String str) {
  21. Matcher matcher = humpPattern.matcher(str);
  22. StringBuffer sb = new StringBuffer();
  23. while (matcher.find()) {
  24. matcher.appendReplacement(sb, "_" + matcher.group( 0).toLowerCase());
  25. }
  26. matcher.appendTail(sb);
  27. return sb.toString();
  28. }
  29. public static void main(String[] args) {
  30. String lineToHump = lineToHump( "f_parent_no_leader");
  31. System.out.println(lineToHump); // fParentNoLeader
  32. System.out.println(humpToLine(lineToHump)); // f_parent_no_leader
  33. System.out.println(humpToLine2(lineToHump)); // f_parent_no_leader
  34. }
  35. }

不糾結""_"+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 yangzhilong
12  *
13  */
14 public class JsonUtils {
15 
16     /**
17      * 將物件的大寫轉換為下劃線加小寫,例如:userName-->user_name
18      * 
19      * @param object
20      * @return
21      * @throws JsonProcessingException
22      */
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-->userName
33      * 
34      * @param json
35      * @param clazz
36      * @return
37      * @throws IOException
38      */
39     public static <T> T toSnakeObject(String json, Class<T> 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     @Test
11     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     @Test
22     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":"張三"}

 

分類: JAVA-雜項, json&jsonp 好文要頂 關注我 收藏該文 自行車上的程式設計師
關注 - 6
粉絲 - 111 +加關注 1 0 « 上一篇: JAVA中的CountDownLatch、CyclicBarrier、Semaphore的簡單測試
» 下一篇: SpringBoot配置RestTemplate的代理和超時時間

實體類:

複製程式碼
 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 yangzhilong
12  *
13  */
14 public class JsonUtils {
15 
16     /**
17      * 將物件的大寫轉換為下劃線加小寫,例如:userName-->user_name
18      * 
19      * @param object
20      * @return
21      * @throws JsonProcessingException
22      */
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-->userName
33      * 
34      * @param json
35      * @param clazz
36      * @return
37      * @throws IOException
38      */
39     public static <T> T toSnakeObject(String json, Class<T> 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     @Test
11     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     @Test
22     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":"張三"}