Ну, если у вас есть JsonElement
объекты, это довольно просто:
private static JsonObject merge(final JsonObject jsonObject1, final JsonObject jsonObject2) {
final JsonObject merged = new JsonObject();
mergeInto(merged, jsonObject1);
mergeInto(merged, jsonObject2);
return merged;
}
private static void mergeInto(final JsonObject destination, final JsonObject source) {
for ( final Map.Entry<String, JsonElement> e : source.entrySet() ) {
destination.add(e.getKey(), e.getValue());
}
}
Или в Java 8 Stream API:
private static JsonObject merge(final JsonObject jsonObject1, final JsonObject jsonObject2) {
return Stream.concat(jsonObject1.entrySet().stream(), jsonObject2.entrySet().stream())
.collect(toJsonObject());
}
private static Collector<Map.Entry<String, JsonElement>, ?, JsonObject> toJsonObject() {
return Collector.of(
JsonObject::new,
(jsonObject, e) -> jsonObject.add(e.getKey(), e.getValue()),
(jsonObject1, jsonObject2) -> {
for ( final Map.Entry<String, JsonElement> e : jsonObject2.entrySet() ) {
jsonObject1.add(e.getKey(), e.getValue());
}
return jsonObject1;
},
Function.identity()
);
}