Compare a json with nested elements after it has been modifed

103 Views Asked by At

I have a usecase where I want to figure out how a json was modified. I have to compare 2 json objects, one before it was modifed and one object representing the state after modfication. The json have many nested objects and arrays in it. The json comparison can be done through RFC 6902 and RFC 7396 which has standard implementations.

The JSON is actually a Java object which has many properties and references to other objects. This causes 2 problems. If the reference id of any child object is updated it would mean the whole object has been replaced rather than just the id field. The other is ordering of objects in collections. I would try to explain the 2 scenarios:

Lets say the id of a child object (car in this case) is modified like below

// initial state
{
  "employee": {
    "id": 1,
    "car": {
      "id": 11,
      "field1": "foo"
    }
  }
}
// modified state
{
  "employee": {
    "id": 1,
    "car": {
      "id": 12,
      "field1": "foo"
    }
  }
}

Then the JSON patch would return {"employee":{"car":{"id":12}}} or [{"op":"replace","path":"/employee/car/id","value":12}] indicating the id was updated. But in my usecase it would mean the existing child object car with id 11 was removed and a new object car with id 12 was placed in its place.

The second problem is in case of collections, the order should not matter. So, the below 2 json comparison would return that the object was not modified.

{
  "employee": {
    "id": 1,
    "cars": [
      {
        "id": 11,
        "field1": "foo"
      },
      {
        "id": 12,
        "field1": "bar"
      }
    ]
  }
}
// modified json
{
  "employee": {
    "id": 1,
    "cars": [
      {
        "id": 12,
        "field1": "bar"
      },
      {
        "id": 11,
        "field1": "foo"
      }
    ]
  }
}

But according to the RFC's the order of the collection matter and changing the index of an item would return an update. For the above change the patch would return {"employee":{"cars":[{"id":12,"field1":"bar"},{"id":11,"field1":"foo"}]}} or

[{"op":"replace","path":"/employee/cars/1/id","value":11},
{"op":"replace","path":"/employee/cars/1/field1","value":"foo"},
{"op":"replace","path":"/employee/cars/0/id","value":12},
{"op":"replace","path":"/employee/cars/0/field1","value":"bar"}]

I can probably write custom code for these two scenarios but I wanted to understand if any json patch implementation (java) can be handle these 2 cases or if there is some library which can support this. Or if someone has an idea how to best approach the problems.

Thanks in advance.

0

There are 0 best solutions below