jsonjacksonjackson-modules

How to do deep merge JSON in jackson 2?


I am using Jersey and Jackson2 to development a Restful API. We have a problem when we development PUT method. Our PUT method is kind of like PATCH method. It will only updates the properties received in the request body.

I am using ObjectMapper.readerForUpdating() method to do object merging. But this method only support first level merge. For instance: I have an existed JSON object

{
  "a": "this is a",
  "b": "this is b",
  "c": {
    "x": 1,
    "y": 2
  }
}

And then I receive a JSON object likes

{
  "a": "this is a new a",
  "c": {
    "x": 3
  }
}

I expect the merged object should be like:

{
  "a": "this is a new a",
  "b": "this is b",
  "c": {
    "x": 3,
    "y": 2
  }
}

But the result is

{
  "a": "this is a new a",
  "b": "this is b",
  "c": {
    "x": 3,
    "y": null
  }
}

The first level properties are merged correctly. But for the deep level, it is doing the object replacement. Is there any way to do deep merge?


Solution

  • At this point, you will have to do that manually by traversing JSON trees (JsonNode) yourself, updating properties. There may be extension libraries that build on Jackson that provide support for this, but core Jackson databind only has "shallow" merge of single (root JSON Object) level.