java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java驼峰与下划线互转

Java实现驼峰与下划线互转的方法

作者:princeAladdin

这篇文章主要为大家详细介绍了Java实现驼峰与下划线互转的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

1.使用 Guava 实现

先引入相关依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

1.1 驼峰转下划线

 public static void main(String[] args) {
        String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName");
        System.out.println("转换后结果是:"+resultStr);
    }

转换后结果是:user_name

1.2 下划线转驼峰

public static void main(String[] args) {
        String resultStr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name");
        System.out.println("转换后结果是:"+resultStr);
    }

转换后结果是:userName

2.自定义代码转

2.1驼峰转下划线

  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下划线转驼峰

  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、另外两种方法

/**
 * 下划线转驼峰
 * @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();
}

/**
 * 驼峰转下划线
 * @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)");
 
    /** 下划线转驼峰 */
    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方法源码即可。

实体类:

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的驼峰和下划线互转帮助类
 *
 *
 */
public class JsonUtils {

    /**
     * 将对象的大写转换为下划线加小写,例如: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;
    }

    /**
     * 将下划线转换为驼峰的形式,例如: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方法可以设置多种配置(例如:多字段 少字段的处理)       //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        T reqJson =  mapper.readValue(json, clazz);
        return reqJson;
    }
}

3.测试

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();
        }
    }
}

测试结果:

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

以上就是Java实现驼峰与下划线互转的方法的详细内容,更多关于Java驼峰与下划线互转的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文