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

Swift中如何比较两个动态JSON对象是否相等?

JSON对象对比失败解决方案

问题根源

你当前使用==直接对比两个JSON对象,本质是在对比对象的内存引用地址:只要两个对象不是同一块内存空间的实例,哪怕内容完全一致,也会返回不相等,这是对比失败的核心原因。
另外你现有代码的判断逻辑中使用的变量名也和实际存储的initialData、modifiedData不匹配,也会导致判断结果异常。

可行解决方案

方案1:序列化后对比字符串(简单场景适用)

将两个JSON对象统一序列化为标准JSON字符串,再对比字符串是否相等,适合JSON结构简单、字段顺序固定的场景,代码实现最简单:

// SwiftyJSON对象可直接调用rawString()获取标准化JSON字符串
guard let initialStr = initialData.rawString(), 
      let modifiedStr = modifiedData.rawString() else {
    print("对象序列化失败,无法完成对比")
    return
}

if initialStr == modifiedStr {
    print("json object are equal save handler")
} else {
    print("json object are not equal save handler")
}

方案2:递归逐字段对比(全场景通用)

通过扩展SwiftyJSON的JSON类型,实现递归逐字段对比逻辑,不受字段排序影响,嵌套结构也能准确识别,是最稳妥的实现方案:

  1. 首先添加扩展:
extension JSON {
    func isEqual(to other: JSON) -> Bool {
        // 类型不同直接返回不相等
        guard self.type == other.type else { return false }
        
        switch self.type {
        case .number:
            return self.numberValue == other.numberValue
        case .string:
            return self.stringValue == other.stringValue
        case .bool:
            return self.boolValue == other.boolValue
        case .array:
            // 数组长度不同直接不相等
            guard self.arrayValue.count == other.arrayValue.count else { return false }
            for (index, item) in self.arrayValue.enumerated() {
                if !item.isEqual(to: other.arrayValue[index]) {
                    return false
                }
            }
            return true
        case .dictionary:
            // 字典key集合不同直接不相等
            guard self.dictionaryValue.keys == other.dictionaryValue.keys else { return false }
            for (key, value) in self.dictionaryValue {
                guard let otherValue = other.dictionaryValue[key], 
                      value.isEqual(to: otherValue) else {
                    return false
                }
            }
            return true
        case .null:
            return true
        default:
            return false
        }
    }
}
  1. 调用对比:
if initialData.isEqual(to: modifiedData) {
    print("json object are equal save handler")
} else {
    print("json object are not equal save handler")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:15:08