代码改变世界

请求参数驼峰转下划线工具类

2022-07-19 00:31  hikoukay  阅读(325)  评论(0编辑  收藏  举报

工具类

/**
* 驼峰转下划线工具类
*/
@Slf4j
public class CamelUnderlineUtil {
    private static boolean camel2Underline;
    
    /*public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    String json = "{\"cId\": 7,\"cname\": \"小六\",\"userId\": \"6\",\"cStatus\": \"Active\"}";
    //        String json = "{\"C_ID\": 7,\"C_NAME\": \"小六\",\"USER_ID\": \"6\",\"C_STATUS\": \"ACTIVE\"}";
    String s = camel2Underline(json);
    log.info(s);
    }*/
    
    /**
    * 驼峰转下划线
    *
    * @param camel
    * @return
    * @throws IOException
    */
    public static String camel2Underline(String camel) throws IOException {
        camel2Underline = true;
        return router(camel);
    }
    
    /**
    * 下划线转驼峰
    *
    * @param camel
    * @return
    * @throws IOException
    */
    public static String underline2Camel(String camel) throws IOException {
        camel2Underline = false;
        return router(camel);
    }
    
    /**
    * 路由类,主要是提取公共方法供上次方法调用
    * @param camel
    * @return
    * @throws IOException
    */
    private static String router(String camel) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper.readValue(camel, Map.class);
        Map<String, Object> newMap = new HashMap<>();
        converMap(map, newMap);
        return objectMapper.writeValueAsString(newMap);
    }
    
    private static void converMap(Map<String, Object> map, Map<String, Object> newMap) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            StringBuilder stringBuilder = new StringBuilder();
            //获取键,对键进行处理
            String key = entry.getKey();
            String newKey = "";
            char[] chars = key.toCharArray();
            if (camel2Underline) {
                for (int i = 0; i < chars.length; ++i) {
                    //如果是大写,就给大写字母前加下划线
                    if (chars[1] >= 'A' & chars[i] <= 'Z') {
                        stringBuilder.append("_").append(chars[i]);
                        //                        stringBuilder.append("_").append(chars[i] = (char) (chars[i] + 32));
                    } else {
                        //否则直接拼接不做处理
                        stringBuilder.append(chars[i]);
                    }
                }
                //全部转化为大写
                newKey = stringBuilder.toString().toUpperCase(Locale.ROOT);
            } else {
                int num = -1;
                for (int i = 0; i < chars.length; i++) {
                    if (num >= 0 && chars[num] == '_') {
                        //下划线后面一位大写
                        stringBuilder.append(String.valueOf(chars[i]).toUpperCase());
                    } else {
                        //首字母及非下划线后面一位小写
                        stringBuilder.append(String.valueOf(chars[i]).toLowerCase());
                    }
                    num++;
                }
                newKey = stringBuilder.toString().replaceAll("_", "");
            }
            
            
            try {
                //获取值,如果值还是对象继续对键进行转化
                Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();
                Map<String, Object> sub = new HashMap<>();
                converMap(valueMap, sub);
                newMap.put(newKey, sub);
            } catch (Exception e) {
                try {
                    List<Map<String, Object>> valueList = (List<Map<String, Object>>) entry.getValue();
                    List<Map<String, Object>> sub = new ArrayList<>();
                    converList(valueList, sub);
                    newMap.put(newKey, sub);
                } catch (Exception V) {
                    newMap.put(newKey, entry.getValue());
                }
            }
        }
    }
    
    private static void converList(List<Map<String, Object>> list, List<Map<String, Object>> newList) {
        for (Map<String, Object> map : list) {
            Map<String, Object> newMap = new HashMap<>();
            converMap(map, newMap);
            newList.add(newMap);
        }
    }
}

 

控制器

/**
 * 驼峰转下划线控制器
 */
@RestController
@RequestMapping("/camelUnderline")
@Slf4j
public class CamelUnderlineController {


    /**
     * 驼峰转下划线
     * @return
     */
    @PostMapping("/camel2Underline")
    public ResponseModel camel2Underline(@RequestBody RequestModel requestModel) throws IOException {
        String stringType = requestModel.getStringType();
        if (StringUtils.isEmpty(stringType)){
            return new ResponseModel("转化的字符串为空", 500, null);
        }
        String result = CamelUnderlineUtil.camel2Underline(stringType);
        JSONObject jsonObject = JSON.parseObject(result);
        return new ResponseModel("驼峰转下划线成功", 200, jsonObject);
    }

    @PostMapping("/underline2Camel")
    public ResponseModel underline2Camel(@RequestBody RequestModel requestModel) throws IOException {
        String stringType = requestModel.getStringType();
        if (StringUtils.isEmpty(stringType)){
            return new ResponseModel("转化的字符串为空", 500, null);
        }
        String result = CamelUnderlineUtil.underline2Camel(stringType);
        JSONObject jsonObject = JSON.parseObject(result);
        return new ResponseModel("下划线转驼峰成功", 200, jsonObject);
    }
}

 

公共类

/**
 * 请求模型
 */
@Data
public class RequestModel implements Serializable {
    /**
     * 字符串类型
     */
    private String stringType;

    /**
     * 数值类型
     */
    private Integer intType;

    /**
     * 集合类型
     */
    private List listType;
    /**
     * map类型类型
     */
    private Map mapType;

}

 

/**
 * 响应结果类
 */
@Data
@ToString
public class ResponseModel implements Serializable {
    //消息
    private String message;
    //状态码
    private int messageCode;
    //结果
    private Object result;

    public ResponseModel(String message, int messageCode, Object result) {
        this.message = message;
        this.messageCode = messageCode;
        this.result = result;
    }

    public ResponseModel() {
    }
}

 

测试报文

下划线转驼峰

{
    "stringType": "{\"C_ID\": 7,\"C_NAME\": \"小六\",\"USER_ID\": \"6\",\"C_STATUS\": \"ACTIVE\",\"ANOTHER_OBJ\": {\"C_ID\": 7,\"C_NAME\": \"小六\",\"USER_ID\": \"6\",\"C_STATUS\": \"ACTIVE\"}}"
}

 

 

 

{
    "stringType": "{\"cId\": 7,\"cName\": \"小六\",\"userId\": \"6\",\"cStatus\": \"Active\",\"anotherObj\": {\"cId\": 7,\"cName\": \"小六\",\"userId\": \"6\",\"cStatus\": \"Active\",\"cStatus\": \"Active\"}}"
}