简体   繁体   中英

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM