Package ca.marcusdunn.jsonlens.mergepatch


@NullMarked package ca.marcusdunn.jsonlens.mergepatch

RFC 7396 JSON Merge Patch: JsonMergePatch and its errors (MergePatchError).

// Keep numbers exact, and reject duplicate names, which have no defined value.
JsonMapper mapper = JsonMapper.builder()
        .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
        .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
        .build();
JsonNode document = mapper.readTree("""
        {"title": "Goodbye!", "author": {"givenName": "John", "familyName": "Doe"}, "tags": ["example", "sample"]}""");
JsonNode patchDocument = mapper.readTree("""
        {"title": "Hello!", "author": {"familyName": null}, "tags": ["example"]}""");

// Read the patch with any model, and merge it in place with an editable model.
// null removes a member, an object merges into a member, and other values replace a member.
Result<JsonNode, MergePatchError> result = JsonMergePatch.parse(patchDocument, JacksonJsonModel.INSTANCE)
        .flatMap(patch -> patch.apply(document, JacksonJsonModel.INSTANCE));
switch (result) {
    case Result.Ok<JsonNode, MergePatchError>(JsonNode root) -> lines.add("merged: " + root);
    case Result.Err<JsonNode, MergePatchError>(MergePatchError error) -> lines.add(error.message());
}
// merged: {"title":"Hello!","author":{"givenName":"John"},"tags":["example"]}