package org.sxkj.common.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Iterator; import java.util.Map; public class CamelKeyToSnakeConverter { public static String formatKey(String json) { // 原始 JSON 字符串(驼峰命名) // 创建 ObjectMapper ObjectMapper mapper = new ObjectMapper(); // 将 JSON 字符串转换为 JsonNode JsonNode rootNode = null; try { rootNode = mapper.readTree(json); } catch (JsonProcessingException e) { throw new RuntimeException(e); } // 递归处理 JSON 键 JsonNode convertedNode = convertKeysToSnakeCase(rootNode); // 将转换后的 JsonNode 重新序列化为 JSON 字符串 String convertedJson = null; try { convertedJson = mapper.writeValueAsString(convertedNode); } catch (JsonProcessingException e) { throw new RuntimeException(e); } System.out.println(convertedJson); return convertedJson; } private static JsonNode convertKeysToSnakeCase(JsonNode node) { if (node.isObject()) { // 处理 JSON 对象 ObjectNode objectNode = (ObjectNode) node; ObjectNode newObjectNode = objectNode.objectNode(); Iterator> fields = objectNode.fields(); while (fields.hasNext()) { Map.Entry field = fields.next(); String newKey = camelToSnakeCase(field.getKey()); // 转换键 newObjectNode.set(newKey, convertKeysToSnakeCase(field.getValue())); // 递归处理值 } return newObjectNode; } else if (node.isArray()) { // 处理 JSON 数组 ArrayNode arrayNode = (ArrayNode) node; ArrayNode newArrayNode = arrayNode.arrayNode(); for (JsonNode item : arrayNode) { newArrayNode.add(convertKeysToSnakeCase(item)); // 递归处理数组中的每个元素 } return newArrayNode; } // 如果是其他类型(如字符串、数字等),直接返回 return node; } private static String camelToSnakeCase(String camelCase) { StringBuilder snakeCase = new StringBuilder(); for (char ch : camelCase.toCharArray()) { if (Character.isUpperCase(ch)) { snakeCase.append('_').append(Character.toLowerCase(ch)); } else { snakeCase.append(ch); } } return snakeCase.toString(); } }