Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add feature to merge objects instead of replace in add operation of p… #129

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/main/java/com/flipkart/zjsonpatch/InPlaceApplyProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.EnumSet;
import java.util.Iterator;

class InPlaceApplyProcessor implements JsonPatchProcessor {

Expand Down Expand Up @@ -142,9 +143,28 @@ else if (parentNode.isArray())
}

private void addToObject(JsonPointer path, JsonNode node, JsonNode value) {
final ObjectNode target = (ObjectNode) node;
String key = path.last().getField();
target.set(key, value);
if (node.has(key) && node.get(key).isObject()) {
mergeInBase(node.get(key), value);
}
else {
final ObjectNode target = (ObjectNode) node;
target.set(key, value);
}
}

public void mergeInBase (JsonNode base, JsonNode value) {
Iterator<String> fieldsIterator = value.fieldNames();

while (fieldsIterator.hasNext()) {
String fieldName = fieldsIterator.next();
if (base.has(fieldName) && base.get(fieldName).isObject()) {
mergeInBase(base.get(fieldName), value.get(fieldName));
} else {
ObjectNode baseObjectNode = (ObjectNode) base;
baseObjectNode.set(fieldName, value.get(fieldName));
}
}
}

private void addToArray(JsonPointer path, JsonNode value, JsonNode parentNode) {
Expand Down