Java遞歸互轉駝峯格式/轉換爲下劃線方法

博主是結合開源hutool StrUtil工具類中toCamelCase、toUnderlineCase方法進行遞歸轉換。https://www.hutool.cn/

/**
     * 轉換爲駝峯格式/轉換爲下劃線方式
     *
     * @param json 等待轉換的方法
     * @param upper 首字母大寫或者小寫
     * @return 轉換後的
     */
    public static JSONObject formatKey(final JSONObject json, boolean upper) {
        JSONObject real = new JSONObject();
        for (String it : json.keySet()) {
            Object objR = json.get(it);
            // 轉換爲駝峯格式/轉換爲下劃線方式
            String key = it.contains("_") ? StrUtil.toCamelCase(it) : StrUtil.toUnderlineCase(it);
            // 首字母大寫或者小寫
            key = upper ? StrUtil.upperFirst(key) : StrUtil.lowerFirst(key);
            if (objR instanceof String) {
                real.put(key, objR);
            }
            if (objR instanceof JSONObject) {
                real.put(key, formatKey((JSONObject) objR, upper));
            }
            if (objR instanceof JSONArray) {
                JSONArray jsonA = new JSONArray();
                for (Object objA : (JSONArray) objR) {
                    jsonA.add(formatKey((JSONObject) objA, upper));
                }
                real.put(key, jsonA);
            }
        }
        return real;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章