I wanna compare two nested JSON objects and get differences between theme like add/remove and change value.
I used JsonDiffer but when I remove one of objects from first or middle of an Array, it detected to change all of the objects.
Pay attention to simple example of my problem please:
The original JSON object is:
{
"Array": [
{
"number": "111",
"Weight": 76
},
{
"number": "222",
"Weight": 77
},
{
"number": "333",
"Weight": 75
}
]
}
and the new is:
{
"Array": [
{
"number": "222",
"Weight": 77
},
{
"number": "333",
"Weight": 75
}
]
}
In this sample JsonDiffer returned all objects in array was changed! In the event that should be returned 111 was removed only.
2
Answers
I finally got the answer to my question with the help of chatGBT
If you need a more dynamic approach, you can use a dictionary-based comparison instead of a fixed model. Let's modify the solution to handle dynamic JSON objects.
In this updated solution, the
DictionaryComparer
compares dictionaries based on their keys and values. Theadded
list will contain the objects present in the first dictionary but not in the second, and theremoved
list will contain the opposite.Remember to adjust the comparison logic if your JSON objects have more complex structures or nested arrays. Feel free to adapt this approach to your specific needs.
Let me know if you have any further questions or need additional assistance! 😊
Check this code:
Model Class:
and the code: