简体   繁体   English

如何比较Swift中的两个JSON对象?

[英]How to compare two JSON objects in Swift?

I have an json object and store it as initialData and after some changes in store the json object into another modifiedData.我有一个 json object 并将其存储为 initialData,经过一些更改后将 json object 存储到另一个修改后的数据中。 Now I am trying to compare two json object of initialData and modifiedData but i could not able to compare it.现在我正在尝试比较两个 json object 的 initialData 和 modifiedData 但我无法比较它。

Note: Here json object are dynamic value.注意:这里的 json object 是动态值。

Sample code:示例代码:

let jsonObjectVal = JSON(message.body)
let initialData = jsonObjectVal

In save action i have modifiedData object.在保存操作中,我修改了数据 object。

 let jsonObjectModVal = JSON(message.body)
 let modifiedData = jsonObjectModVal

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

Any help much appreciated pls...非常感谢任何帮助...

Here's an example with a random data structure on how exactly you can do it:这是一个带有随机数据结构的示例,说明您可以如何做到这一点:

import Foundation

final class YourObject: Decodable, Equatable {

    var field1: String
    var field2: Int
    var field3: [String : Double]

    static func == (lhs: YourObject, rhs: YourObject) -> Bool {
        lhs.field1 == rhs.field1
            && lhs.field2 == rhs.field2
            && lhs.field3 == rhs.field3
    }

}

let firstJSONString = """
{
   "field1":"Some string",
   "field2":1,
   "field3":{
      "Some string":2
   }
}
"""
let firstJSONData = firstJSONString.data(using: .utf8)!
let firstObject = try? JSONDecoder().decode(YourObject.self, from: firstJSONData)

let secondJSONString = """
{
   "field1":"Some string",
   "field2":1,
   "field3":{
      "Some string":2
   }
}
""" // Same.
let secondJSONData = secondJSONString.data(using: .utf8)!
let secondObject = try? JSONDecoder().decode(YourObject.self, from: secondJSONData)

let thirdJSONString = """
{
   "field1":"Some other string",
   "field2":2,
   "field3":{
      "Some string":3
   }
}
""" // Differs.
let thirdJSONData = thirdJSONString.data(using: .utf8)!
let thirdObject = try? JSONDecoder().decode(YourObject.self, from: thirdJSONData)

print(firstObject == secondObject) // true
print(firstObject == thirdObject) // false

Note: You mentioned that the object should be dynamic, that's why it's a class .注意:您提到 object 应该是动态的,这就是为什么它是class的原因。 If you needed a value object, you would be able to use struct and avoid manual implementation of the == operator.如果您需要一个值 object,您将能够使用struct并避免手动实现==运算符。

It's just a start of course.当然,这只是一个开始。 Having a specific JSON structure in your hands you can always search for more complicated examples, internet swarms with them.拥有一个特定的 JSON 结构,您可以随时搜索更复杂的示例,互联网蜂拥而至。

Create a NSObject class or struct from the JSON and compare all the properties to check for equality and return true/false accordingly.从 JSON 创建一个 NSObject class 或结构并比较所有属性以检查是否相等并相应地返回真/假。 Equatable protocol will come in handy here. Equatable 协议将在这里派上用场。

class A: Equatable {
    func equalTo(rhs: A) -> Bool {
        // whatever equality means for two As
    }
}

func ==(lhs: A, rhs: A) -> Bool {
    return lhs.equalTo(rhs)
}

For Compare 2 objects use === operator对于比较 2 个对象,请使用===运算符

for eg.例如。

let jsonObjectModVal = JSON(message.body)
 let modifiedData = jsonObjectModVal

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

If you want to compare two completely arbitrary JSON objects (eg for unit testing), I'd suggest using the GenericJSON library.如果您想比较两个完全任意的 JSON 对象(例如用于单元测试),我建议使用GenericJSON库。 Add it to your project and/or Package.swift, and then (borrowing from @lazarevzubov's answer):将它添加到您的项目和/或 Package.swift,然后(借用@lazarevzubov 的回答):

import GenericJSON

// Assume `YourObject` is `Encodable`
let testObject = YourObject(field1: "Some string", field2: 1, field3: ["Some string": 2])

let expectedData = """
{
   "field1":"Some string",
   "field2":1,
   "field3":{
      "Some string":2
   }
}
""".data(using: .utf8)!

let expectedJSON = try? JSON(JSONSerialization.jsonObject(with: expectedData))
let actualJSON = try? JSON(encodable: testObject)

XCTAssertEqual(actualJSON, expectedJSON, "JSON should be equal")

A nice bonus is that you don't need to add any otherwise unnecessary Decodable or Equatable conformance to your model objects.一个不错的好处是您不需要向 model 对象添加任何其他不必要的DecodableEquatable一致性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM