Skip to content

Examples

Oswaldo Baptista Vicente Junior edited this page Aug 17, 2022 · 11 revisions

Merge two JSON Objects using json-smart as provider

Suppose you have the following JSON documents previously loaded using json-smart as provider:

  • JSONObject json1

    {
      "agents": [
        {
          "class": "Agent1",
          "interval": "1 minute"
        },
        {
          "class": "Agent2",
          "interval": "2 minutes"
        }
      ]
    }
  • JSONObject json2

    {
      "agents": [
        {
          "class": "Agent2",
          "interval": "2 hours"
        },
        {
          "class": "Agent3",
          "interval": "3 minutes"
        }
      ]
    }
  1. Create a JsonMerger of type net.minidev.json.JSONObject with the JsonSmartJsonProvider:
import net.minidev.json.JSONObject;
import net.obvj.jsonmerge.*;
import net.obvj.jsonmerge.provider.JsonSmartJsonProvider;
...
JsonMerger<JSONObject> merger = new JsonMerger<>(new JsonSmartJsonProvider());
  1. Merge both objects, defining a distinct key class to identify each object in the agents list:
JSONObject merged = merger.merge(json1, json2,
        JsonMergeOption.distinctKey("$.agents", "class"));

💡 The JSON generated by the merge operation will be as follows:

{
  "agents": [
    {
      "class": "Agent1",
      "interval": "1 minute"
    },
    {
      "class": "Agent2",
      "interval": "2 minutes"
    },
    {
      "class": "Agent3",
      "interval": "3 minutes"
    }
  ]
}
🔝 Back to top

Clone this wiki locally