Java实现JSON所有Key转为大写(含嵌套数组/对象)求助
JSON所有Key转大写的Java解决方案
为什么不推荐用正则表达式?
用replaceAll这类正则方法处理JSON风险极高,因为无法区分真正的Key和字符串值里类似Key格式的内容。比如JSON里如果有"name": "my\"id\"is123",正则会误把值里的id也转成大写,破坏JSON结构和内容。而且嵌套的数组、多层对象的结构也不是简单正则能覆盖的,很容易遗漏或误处理。
正确方案:用JSON解析库处理
推荐用Jackson或Gson这两个Java生态最常用的JSON库,能安全遍历并修改所有Key,包括嵌套对象和数组里的对象。
方案1:使用Jackson库
- 先添加Maven依赖(Gradle同理):
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- 用最新稳定版即可 --> </dependency>
- 编写递归转换代码:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Iterator; import java.util.Map; public class JsonKeyUpperConverter { private static final ObjectMapper objectMapper = new ObjectMapper(); public static String convertKeysToUpper(String jsonStr) throws Exception { JsonNode rootNode = objectMapper.readTree(jsonStr); JsonNode convertedNode = convertNode(rootNode); return objectMapper.writeValueAsString(convertedNode); } private static JsonNode convertNode(JsonNode node) { if (node.isObject()) { ObjectNode objectNode = objectMapper.createObjectNode(); Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String upperKey = entry.getKey().toUpperCase(); JsonNode convertedValue = convertNode(entry.getValue()); objectNode.set(upperKey, convertedValue); } return objectNode; } else if (node.isArray()) { JsonNode arrayNode = objectMapper.createArrayNode(); for (int i = 0; i < node.size(); i++) { arrayNode.add(convertNode(node.get(i))); } return arrayNode; } else { // 字符串、数字、布尔、null等基本类型直接返回 return node; } } public static void main(String[] args) throws Exception { String inputJson = "{\"name\":\"Alice\",\"age\":25,\"address\":{\"street\":\"Main St\",\"city\":\"NY\"},\"hobbies\":[{\"type\":\"reading\",\"book\":\"Java Guide\"}]}"; String outputJson = convertKeysToUpper(inputJson); System.out.println(outputJson); } }
这段代码会递归遍历所有JSON节点:
- 遇到对象时,将每个Key转大写后重新存入新对象,同时递归处理对应的值
- 遇到数组时,遍历数组内每个元素并递归处理
- 基本类型直接原样返回
方案2:使用Gson库
- 添加Maven依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- 最新稳定版 --> </dependency>
- 编写转换代码:
import com.google.gson.*; import java.util.Map; public class GsonKeyUpperConverter { private static final Gson gson = new Gson(); public static String convertKeysToUpper(String jsonStr) { JsonElement rootElement = JsonParser.parseString(jsonStr); JsonElement convertedElement = convertElement(rootElement); return gson.toJson(convertedElement); } private static JsonElement convertElement(JsonElement element) { if (element.isJsonObject()) { JsonObject jsonObject = element.getAsJsonObject(); JsonObject newJsonObject = new JsonObject(); for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { String upperKey = entry.getKey().toUpperCase(); JsonElement convertedValue = convertElement(entry.getValue()); newJsonObject.add(upperKey, convertedValue); } return newJsonObject; } else if (element.isJsonArray()) { JsonArray jsonArray = element.getAsJsonArray(); JsonArray newJsonArray = new JsonArray(); for (JsonElement item : jsonArray) { newJsonArray.add(convertElement(item)); } return newJsonArray; } else { // 基本类型直接返回 return element; } } public static void main(String[] args) { String inputJson = "{\"name\":\"Bob\",\"age\":30,\"contact\":{\"email\":\"bob@test.com\",\"phone\":\"123456\"},\"skills\":[{\"name\":\"Java\",\"level\":\"advanced\"}]}"; String outputJson = convertKeysToUpper(inputJson); System.out.println(outputJson); } }
逻辑和Jackson版本一致,通过递归遍历确保所有嵌套层级的Key都被转成大写。
内容的提问来源于stack exchange,提问作者Java BEE
相关产品推荐
相关产品推荐

