Charith Hettiarachchi
Charith Hettiarachchi

Reputation: 432

Merge several json objects Java with jackson

I use a java delegate and use the getVariable to read the execution variables. Within the execution variables, I have many stringified JSON objects. I loop through all the objects and read create a json node in the following way,

for (String name: execution.getVariableNames()) {
    JsonNode data = objectMapper.readTree(execution.getVariable(name).toString());
    System.out.println(data);
 }

I get all the individual JSON objects from the above for loop.

{"username": "testUser", "company": "TestCompany"}
{"app": "testApp", "subscriberCount": 20000}
{"appCount": 20}

The above is an example of the output I receive. What I would like is to combine the above json objects to a single json objects within the loop. The output should be something like this.

{
   "username": "testUser",
   "company": "TestCompany",
   "app": "testApp",
   "subscriberCount": 20000,
   "appCount": 20
}

I want to merge all the objects dynamically. Which means I don't want to consider the data that are in the json objects when merging them.

Upvotes: 0

Views: 2229

Answers (1)

Ethan McTague
Ethan McTague

Reputation: 2358

You could produce a new object and iterate over the fields in your existing data objects to assign them to the new object.

This existing answer shows how to merge objects by iterating over their fields. It performs a deeper-level merge, but to simply merge top-level keys you might do something like this for each data object to put their fields into a single ObjectNode:

ObjectNode merged = objectMapper.createObjectNode();
for (String name: execution.getVariableNames()) {
    JsonNode data = objectMapper.readTree(execution.getVariable(name).toString());
    data.fields()
        .forEachRemaining(f -> merged.putIfAbsent(f.getKey(), f.getValue()));
}

(The forEachRemaining line is the relevant one to add keys from one object to another in this case.)

Upvotes: 3

Related Questions