Class JsonMergePatch

java.lang.Object
cloud.opencode.base.json.patch.JsonMergePatch

public final class JsonMergePatch extends Object
JSON Merge Patch - RFC 7396 Implementation JSON Merge Patch - RFC 7396 实现

This class implements JSON Merge Patch (RFC 7396), which provides a simpler way to apply partial modifications to a JSON document.

此类实现 JSON Merge Patch(RFC 7396),提供一种更简单的方式 对 JSON 文档进行部分修改。

Rules | 规则:

  • If patch is not an object, replace the target - 如果补丁不是对象,替换目标
  • For each property in the patch object: - 对于补丁对象中的每个属性:
    • If value is null, remove the property - 如果值为 null,移除属性
    • Otherwise, recursively merge - 否则,递归合并

Example | 示例:

JsonNode target = OpenJson.parse("{\"name\":\"John\",\"age\":30,\"city\":\"NYC\"}");
JsonNode patch = OpenJson.parse("{\"age\":31,\"city\":null,\"email\":\"john@example.com\"}");

JsonNode result = JsonMergePatch.apply(target, patch);
// Result: {"name":"John","age":31,"email":"john@example.com"}

// Using builder
JsonNode result2 = JsonMergePatch.builder()
    .set("name", "Jane")
    .remove("age")
    .set("email", "jane@example.com")
    .apply(target);

Features | 主要功能:

  • RFC 7396 JSON Merge Patch implementation - RFC 7396 JSON Merge Patch实现
  • Recursive merge of JSON object hierarchies - JSON对象层次结构的递归合并
  • Diff generation between two JSON documents - 两个JSON文档之间的差异生成

Security | 安全性:

  • Thread-safe: Yes (immutable) - 线程安全: 是(不可变)
  • Null-safe: Partial (validates inputs) - 空值安全: 部分(验证输入)
Since:
JDK 25, opencode-base-json V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • of

      public static JsonMergePatch of(JsonNode patch)
      Creates a merge patch from a JsonNode. 从 JsonNode 创建合并补丁。
      Parameters:
      patch - the patch node - 补丁节点
      Returns:
      the merge patch - 合并补丁
    • builder

      public static JsonMergePatch.Builder builder()
      Creates a new builder. 创建新的构建器。
      Returns:
      a new builder - 新构建器
    • apply

      public static JsonNode apply(JsonNode target, JsonNode patch)
      Applies a merge patch to a target. 将合并补丁应用于目标。
      Parameters:
      target - the target document - 目标文档
      patch - the patch document - 补丁文档
      Returns:
      the merged result - 合并结果
    • apply

      public JsonNode apply(JsonNode target)
      Applies this patch to a target. 将此补丁应用于目标。
      Parameters:
      target - the target document - 目标文档
      Returns:
      the merged result - 合并结果
    • getPatch

      public JsonNode getPatch()
      Returns the patch content. 返回补丁内容。
      Returns:
      the patch - 补丁
    • diff

      public static JsonMergePatch diff(JsonNode source, JsonNode target)
      Creates a diff patch between two documents. 创建两个文档之间的差异补丁。
      Parameters:
      source - the source document - 源文档
      target - the target document - 目标文档
      Returns:
      the merge patch that transforms source to target - 将源转换为目标的合并补丁