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

深度嵌套JsonObject/JsonArray中检索特定值的最优方案

问题根因

你原有实现的问题在于:List.contains(null) 只会检查列表的最外层元素,不会对嵌套的数组、Map结构做深度遍历,因此无法识别嵌套层级的null值。同时将JsonNode转成List的额外序列化操作也会带来不必要的性能开销。

最优实现方案

直接基于Jackson原生的JsonNodeAPI实现递归深度扫描,不需要做类型转换,即可适配任意嵌套结构的null检查:

1. 编写递归扫描工具方法

/**
 * 深度扫描JsonNode节点下是否存在null值
 * @param node 待扫描的根节点
 * @return 存在null返回true,不存在返回false
 */
private boolean hasNullNode(JsonNode node) {
    // 节点本身为null直接返回结果
    if (node == null || node.isNull()) {
        return true;
    }
    // 数组类型遍历所有元素递归检查
    if (node.isArray()) {
        for (JsonNode element : node) {
            if (hasNullNode(element)) {
                return true;
            }
        }
    }
    // 对象(Map)类型遍历所有属性值递归检查
    if (node.isObject()) {
        Iterator<JsonNode> fieldValueIterator = node.elements();
        while (fieldValueIterator.hasNext()) {
            if (hasNullNode(fieldValueIterator.next())) {
                return true;
            }
        }
    }
    // 普通值类型无null
    return false;
}

2. 改造原有业务逻辑

for (Map.Entry<String, DataType> allowedKey : allowedKeys.entrySet()) {
    JsonNode targetNode = contentAsNode.get(allowedKey.getKey());
    // 跳过不存在的key,可根据业务需求调整为报错逻辑
    if (targetNode == null) {
        continue;
    }
    try {
        if (hasNullNode(targetNode)) {
            this.errorType = ErrorType.NULL_ARRAY_ELEMENT;
            return false;
        }
    } catch (Exception e) {
        this.errorType = ErrorType.BODY_NOT_PARSEABLE;
        return false;
    }
}

方案优势

  • 适配任意结构:无需提前知道目标key对应值的结构,支持单层数组、嵌套数组、对象、多层嵌套等所有场景
  • 性能更高:省去了JsonNode转List/Map的序列化开销,直接操作原生节点效率更高
  • 逻辑简洁:递归方法可复用,不需要针对不同结构写多套判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 00:54:03