JsonUtil.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package com.usky.utils;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. /**
  5. * @author 我去喂猪了
  6. * @version v1.0
  7. * @date 2020/9/12 14:35
  8. * @description TODO
  9. **/
  10. public class JsonUtil {
  11. private static Pattern linePattern = Pattern.compile("_(\\w)");
  12. /** 下划线转驼峰 */
  13. public static String lineToHump(String str) {
  14. str = str.toLowerCase();
  15. Matcher matcher = linePattern.matcher(str);
  16. StringBuffer sb = new StringBuffer();
  17. while (matcher.find()) {
  18. matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
  19. }
  20. matcher.appendTail(sb);
  21. return sb.toString();
  22. }
  23. /** 驼峰转下划线(简单写法,效率低于{@link #humpToLine2(String)}) */
  24. public static String humpToLine(String str) {
  25. return str.replaceAll("[A-Z]", "_$0").toLowerCase();
  26. }
  27. private static Pattern humpPattern = Pattern.compile("[A-Z]");
  28. /** 驼峰转下划线,效率比上面高 */
  29. public static String humpToLine2(String str) {
  30. Matcher matcher = humpPattern.matcher(str);
  31. StringBuffer sb = new StringBuffer();
  32. while (matcher.find()) {
  33. matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
  34. }
  35. matcher.appendTail(sb);
  36. return sb.toString();
  37. }
  38. public static void main(String[] args) {
  39. String lineToHump = lineToHump("{\"device_code\":\"12321312332313\",\"company_code\":\"\",\"device_name\":\"1223\",\"transmission_mode\":\"1\",\"device_types\":\"3\",\"device_model\":\"6\",\"data\":\"1\",\"device_install\":\"1\",\"device_floor\":\"1\",\"sim\":\"11\",\"manufactor_name\":\"无锡蓝天\",\"installer\":\"1\",\"magnification\":\"\",\"model_corresponding_method\":\"\",\"ports\":\"0\",\"highest_floor\":\"1\",\"lowest_floor\":\"1\",\"top_level_label\":\"0\",\"ownerId\":\"0\",\"device_type\":\"Smoke\",\"is_secure\":\"0\",\"status\":\"1\",\"protocol_type\":\"CoPA\",\"location\":\"黄浦区\",\"model\":\"\",\"psk\":\"c78af7fe1406eaad0898cce15b6e15f1\",\"iot_id\":\"7662fe48-2cdb-467f-869e-dd6a6babf8c4\",\"ownerCode\":\"YT100036000010000001\",\"number\":\"10000001\"}");
  40. System.out.println(lineToHump);// fParentNoLeader
  41. }
  42. }