json字符串中下划线’_’转驼峰

内容纲要

JsonSnakeToCamel.java

import com.fasterxml.jackson.databind.JsonNode;  
import com.fasterxml.jackson.databind.ObjectMapper;  
import com.fasterxml.jackson.databind.node.ObjectNode;  
import com.google.common.base.CaseFormat;  

import java.util.ArrayList;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  

public class JsonSnakeToCamel {  

    // 将下划线转换为驼峰命名的方法  
    private static String convertToCamelCase(String snakeCase) {  
        StringBuilder result = new StringBuilder();  
        boolean nextUpperCase = false;  

        for (char c : snakeCase.toCharArray()) {  
            if (c == '_') {  
                nextUpperCase = true;  
            } else if (nextUpperCase) {  
                result.append(Character.toUpperCase(c));  
                nextUpperCase = false;  
            } else {  
                result.append(c);  
            }  
        }  
        return result.toString();  
    }  

    /**使用guava工具进行驼峰转换*/  
    public static String convertToCamelCaseNew(String snakeCase){  
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,snakeCase);  
    }  

    // 递归处理 JSON 对象,将下划线命名的 key 转换为驼峰命名  
    private static void convertJsonNodeToCamelCase(JsonNode rootNode) {  
        if (rootNode.isObject()) {  
            ObjectNode objectNode = (ObjectNode) rootNode;  
            List<String> keysToRemove = new ArrayList<>();  
            List<Map.Entry<String, JsonNode>> newEntries = new ArrayList<>();  

            // 遍历所有字段  
            Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();  

            while (fields.hasNext()) {  
                Map.Entry<String, JsonNode> field = fields.next();  
                String snakeCaseKey = field.getKey();  
                JsonNode value = field.getValue();  

                // 将下划线命名的 key 转换为驼峰命名  
                //String camelCaseKey = convertToCamelCase(snakeCaseKey);  
                String camelCaseKey = convertToCamelCaseNew(snakeCaseKey);  

                // 递归处理子节点  
                convertJsonNodeToCamelCase(value);  

                // 如果 key 需要改变,记录要移除的旧 key 和要添加的新 key               
                if (!snakeCaseKey.equals(camelCaseKey)) {  
                    keysToRemove.add(snakeCaseKey);  
                    newEntries.add(new Map.Entry<String, JsonNode>() {  
                        @Override  
                        public String getKey() {  
                            return camelCaseKey;  
                        }  

                        @Override  
                        public JsonNode getValue() {  
                            return value;  
                        }  

                        @Override  
                        public JsonNode setValue(JsonNode value) {  
                            return null;  
                        }  
                    });  
                }  
            }  

            // 移除旧的 key            
            for (String key : keysToRemove) {  
                objectNode.remove(key);  
            }  

            // 添加新的 key-value 对  
            for (Map.Entry<String, JsonNode> entry : newEntries) {  
                objectNode.set(entry.getKey(), entry.getValue());  
            }  

        } else if (rootNode.isArray()) {  
            // 处理数组中的每一个元素  
            for (JsonNode arrayElement : rootNode) {  
                convertJsonNodeToCamelCase(arrayElement);  
            }  
        }  
    }  

    public static String convertJsonSnakeToCamel(String json) throws Exception {  
        ObjectMapper mapper = new ObjectMapper();  

        // 将 JSON 字符串解析为 JsonNode        
        JsonNode rootNode = mapper.readTree(json);  

        // 递归转换 JsonNode        
        convertJsonNodeToCamelCase(rootNode);  

        // 将修改后的 JsonNode 转换回 JSON 字符串  
        return mapper.writeValueAsString(rootNode);  
    }  

    public static void main(String[] args) throws Exception {  
        String json = "{ \"first_name\": \"John\", \"last_name\": \"Doe\", \"address\": { \"street_name\": \"Main St\", \"zip_code\": \"12345\" }, \"hobbies\": [{\"hobby_name\": \"reading\"}, {\"hobby_name\": \"sports\"}] }";
        String result = convertJsonSnakeToCamel(json);  
        System.out.println(result);  
    }  
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注