eclipse-vertx / eclipse-vertx/vert.x

JsonObject : add further options on how to mergeIn JsonObject

Open
#5,453 2 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
14.7k
Forks
2.1k
Avg merge
2d 7h
Merged PRs (30d)
28

Description

#### Describe the feature

currently config files are merged by overwriting null values and by overwriting array values.
in my use case however, array values need to be merged and null values should not override existing values.
example:

> JsonObject o1 = JsonObject.of("m", null, "a", JsonArray.of(1));
JsonObject o2 = JsonObject.of("m", JsonObject.of(), "a", JsonArray.of(2));
JsonObject o3 = o2.mergeIn(o1, true, true, false);
System.out.println(o3);

should return:
>{"m":{},"a":[1,2]}

#### Use cases

rational: configuration files are structured by module. a module may have a property which is not included in another, therefore null value should not override a non null value.

the values of arrays may need to be "collected" over multiple module configurations.

#### Contribution

JsonObject.java:

> public JsonObject mergeIn(JsonObject other, int depth, boolean mergeArrays, boolean overwriteNull) {
if (depth < 1) {
return this;
}
if (depth == 1 && !mergeArrays && overwriteNull) {
map.putAll(other.map);
return this;
}
for (Map.Entry e : other.map.entrySet()) {
if (e.getValue() == null && overwriteNull) {
map.put(e.getKey(), null);
} else if (e.getValue() != null){
map.merge(e.getKey(), e.getValue(), (oldVal, newVal) -> {
if (oldVal instanceof Map) {
oldVal = new JsonObject((Map) oldVal);
}
if (newVal instanceof Map) {
newVal = new JsonObject((Map) newVal);
}
if (mergeArrays && oldVal instanceof JsonArray && newVal instanceof JsonArray)
return ((JsonArray)newVal).addAll((JsonArray)oldVal);
if (oldVal instanceof JsonObject && newVal instanceof JsonObject) {
return ((JsonObject) oldVal).mergeIn((JsonObject) newVal, depth - 1, mergeArrays, overwriteNull);
}
return newVal;
});
}
}
return this;
}

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.