I have an json object and store it as initialData and after some changes in store the json object into another modifiedData. Now I am trying to compare two json object of initialData and modifiedData but i could not able to compare it.
Note: Here json object are dynamic value.
Sample code:
let jsonObjectVal = JSON(message.body)
let initialData = jsonObjectVal
In save action i have modifiedData 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…
4
Answers
Create a NSObject class or struct from the JSON and compare all the properties to check for equality and return true/false accordingly.
Equatable protocol will come in handy here.
Here’s an example with a random data structure on how exactly you can do it:
Note: You mentioned that the object should be dynamic, that’s why it’s a
class
. If you needed a value object, you would be able to usestruct
and avoid manual implementation of the==
operator.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.
For Compare 2 objects use === operator
for eg.
If you want to compare two completely arbitrary JSON objects (e.g. for unit testing), I’d suggest using the GenericJSON library. Add it to your project and/or Package.swift, and then (borrowing from @lazarevzubov’s answer):
A nice bonus is that you don’t need to add any otherwise unnecessary
Decodable
orEquatable
conformance to your model objects.