You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用org.json.JSONObject重命名嵌套及数组内JSON键方案

JSON动态键重命名实现方案

基于org.json.JSONObject的原生递归实现

你当前的代码仅处理了顶层对象的键,核心缺失是全节点深度遍历逻辑。通过递归遍历所有嵌套结构,即可覆盖对象嵌套、数组嵌套的任意动态JSON结构场景,不需要提前预知JSON格式。
递归处理逻辑规则:

  • 遍历JSONObject节点时,先匹配当前层键名执行重命名,再对每个键对应的值做类型判断递归
  • 遍历JSONArray节点时,逐个取出数组元素做类型判断递归
  • 遇到字符串、数字、布尔、null等基础类型值时直接跳过
    可直接复用的工具类代码:
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class JsonKeyRenameUtil {
    private static final Logger LOG = LoggerFactory.getLogger(JsonKeyRenameUtil.class);

    /**
     * 全局深度重命名JSON中匹配的键
     * @param jsonObject 待处理JSON对象
     * @param keyMapping 重命名映射:key=原键名,value=新键名
     */
    public static void deepRenameKeys(JSONObject jsonObject, Map<String, String> keyMapping) {
        if (jsonObject == null || keyMapping == null || keyMapping.isEmpty()) {
            return;
        }
        // 先拷贝当前层所有键,避免遍历中修改结构触发并发修改异常
        Iterator<String> keyIterator = jsonObject.keys();
        List<String> currentKeys = new ArrayList<>();
        while (keyIterator.hasNext()) {
            currentKeys.add(keyIterator.next());
        }

        for (String key : currentKeys) {
            Object value = jsonObject.get(key);
            // 处理当前层键重命名
            if (keyMapping.containsKey(key)) {
                String newKey = keyMapping.get(key);
                try {
                    jsonObject.put(newKey, jsonObject.remove(key));
                    LOG.trace("Renaming Field {} with Field {}", key, newKey);
                    key = newKey;
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
            // 递归处理嵌套值
            processNestedValue(value, keyMapping);
        }
    }

    private static void processNestedValue(Object value, Map<String, String> keyMapping) {
        if (value instanceof JSONObject) {
            deepRenameKeys((JSONObject) value, keyMapping);
        } else if (value instanceof JSONArray) {
            JSONArray array = (JSONArray) value;
            for (int i = 0; i < array.length(); i++) {
                processNestedValue(array.get(i), keyMapping);
            }
        }
    }
}

调用示例:

// 构造重命名映射
Map<String, String> renameRule = new HashMap<>();
renameRule.put("email", "contactEmail");
renameRule.put("supportingCustomerName", "customerName");
// 传入原始JSON对象执行重命名
JSONObject originJson = new JSONObject(/* 原始JSON字符串/对象 */);
JsonKeyRenameUtil.deepRenameKeys(originJson, renameRule);

如果需要按指定路径重命名(比如仅重命名contactInformation.contact.email,其他层级的email不处理),只需要给递归方法增加当前路径参数,遍历过程中拼接完整节点路径,匹配目标路径时再执行重命名即可,扩展成本极低。

可选成熟类库方案

如果不想自行维护递归遍历逻辑,可以使用Java生态成熟的JSON处理类库,基于其内置的树遍历能力可以快速实现相同能力:

  • Jackson:Java生态最常用的JSON库,基于JsonNode做树遍历实现重命名逻辑,性能优于org.json,稳定性高
  • Gson:通过JsonElement做树结构遍历,API简洁易上手
  • Fastjson2:内置节点遍历相关API,处理速度快,注意选择无安全漏洞的正式版本使用

内容的提问来源于stack exchange,提问作者Rocky4Ever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 15:39:14