Class JsonCanonicalizer
java.lang.Object
cloud.opencode.base.json.util.JsonCanonicalizer
JSON Canonicalizer - RFC 8785 JSON Canonicalization Scheme (JCS)
JSON 规范化器 - RFC 8785 JSON 规范化方案 (JCS)
Implements the JSON Canonicalization Scheme defined in RFC 8785, producing deterministic JSON output suitable for digital signatures, hashing, and comparison.
实现 RFC 8785 中定义的 JSON 规范化方案, 生成适用于数字签名、哈希和比较的确定性 JSON 输出。
Features | 主要功能:
- Object keys sorted by UTF-16 code unit values - 对象键按 UTF-16 代码单元值排序
- No whitespace between tokens - 标记之间无空白
- ECMAScript ES6 number serialization - ECMAScript ES6 数字序列化
- Minimal string escaping (only required escapes) - 最小化字符串转义
- Recursive with configurable depth limit (1000) - 递归处理,深度限制 1000
Usage Examples | 使用示例:
// Canonicalize a JsonNode
JsonNode node = JsonNode.object().put("b", 2).put("a", 1);
String canonical = JsonCanonicalizer.canonicalize(node);
// Result: {"a":1,"b":2}
// Canonicalize a JSON string
String canonical = JsonCanonicalizer.canonicalize("{\"b\":2,\"a\":1}");
// Result: {"a":1,"b":2}
Performance | 性能:
- Single-pass tree traversal with StringBuilder output - 单遍树遍历,StringBuilder 输出
- No intermediate object creation for primitives - 原始类型无中间对象创建
Security | 安全性:
- Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具类)
- Depth limit prevents stack overflow from deeply nested input - 深度限制防止深层嵌套输入的栈溢出
- Rejects NaN and Infinity (not valid JSON) - 拒绝 NaN 和 Infinity(非法 JSON)
- Since:
- JDK 25, opencode-base-json V1.0.3
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic Stringcanonicalize(JsonNode node) Canonicalizes a JsonNode according to RFC 8785 JCS.static Stringcanonicalize(String json) Canonicalizes a JSON string according to RFC 8785 JCS.
-
Method Details
-
canonicalize
Canonicalizes a JsonNode according to RFC 8785 JCS. 按照 RFC 8785 JCS 规范化 JsonNode。- Parameters:
node- the JSON node to canonicalize - 要规范化的 JSON 节点- Returns:
- the canonicalized JSON string - 规范化后的 JSON 字符串
- Throws:
OpenJsonProcessingException- if the node is null, contains NaN/Infinity, or exceeds depth limit - 如果节点为 null、包含 NaN/Infinity 或超过深度限制
-
canonicalize
Canonicalizes a JSON string according to RFC 8785 JCS. 按照 RFC 8785 JCS 规范化 JSON 字符串。Convenience method that parses the input string into a tree and then canonicalizes it.
便捷方法,先将输入字符串解析为树,再进行规范化。
- Parameters:
json- the JSON string to canonicalize - 要规范化的 JSON 字符串- Returns:
- the canonicalized JSON string - 规范化后的 JSON 字符串
- Throws:
OpenJsonProcessingException- if the input is null, invalid JSON, contains NaN/Infinity, or exceeds depth limit - 如果输入为 null、无效 JSON、包含 NaN/Infinity 或超过深度限制
-