数据校验
SJF4J 可以直接通过 JSON Schema 校验 Java 对象,无需先序列化或构建中间 JSON 树。支持 Draft 2020-12、2019-09 和 7,同时提供灵活的 Runtime 校验和编译期生成的校验器。
适用于 POJO、Map、List、SJF4J 节点及受支持的External Nodes。
快速开始
从普通 Java 对象开始:
class User {
public String name;
public int age;
}在 src/main/resources/schemas/user.json 中定义 Schema。下面的两种方式都使用该文件:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"description": "A user record",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["name"]
}Runtime 校验需要 sjf4j-schema;Compiled 校验还需要将 sjf4j-processor 加入注解处理器路径。Gradle 和 Maven 配置参阅安装指南。
Runtime Validation
解析一次 JSON Schema,创建可复用的 SchemaPlan,直接校验 Java 对象。这里的 schemaJson 包含上面的 JSON Schema:
SchemaPlan plan = JsonSchema.fromJson(schemaJson).formulate();
User user = new User();
user.name = "Alice";
user.age = 18;
boolean valid = plan.isValid(user);
ValidationResult result = plan.validate(user);
plan.requireValid(user);根据需要选择返回方式:
| API | 行为 |
|---|---|
isValid(value) | 快速校验,失败即停止,返回布尔值 |
validate(value) | 收集校验错误 |
requireValid(value) | 校验失败时抛出 ValidationException |
错误与注解
ValidationResult 提供失败的关键字、错误消息、实例位置和 Schema 位置:
user.name = "";
ValidationResult errors = plan.validate(user);
for (ValidationResult.Detail error : errors.getErrors()) {
System.out.println(error.getKeyword() + ": "
+ error.getInstancePs().rootedPointerExpr()
+ " - " + error.getMessage());
}如需控制失败即停止、严格的 format 断言或收集 JSON Schema 注解,可使用 ValidationOptions:
user.name = "Alice"; // Restore a valid instance.
ValidationOptions options = ValidationOptions.builder()
.collectAnnotations(true)
.build();
ValidationResult annotated = plan.validate(user, options);
annotated.getAnnotations(); // title, description, default, examples, etc.注解收集是可选的。默认情况下,SchemaPlan 将 format 视为注解而非断言;启用 strictFormat 后会校验受支持的格式。
Compiled Validation
@CompiledValidator 在注解处理阶段生成 Java 校验代码。它使用与 Runtime 校验相同的 Schema 和 Java 模型:
@CompiledValidator
interface UserValidator {
@ValidJsonSchema(ref = "classpath:/schemas/user.json")
boolean isValid(User user);
}
UserValidator validator = CompiledInstances.create(UserValidator.class);
boolean valid = validator.isValid(user);生成实现名为 UserValidator_Impl。重复校验时应复用实例;对于支持直接编译的规则,生成代码可避免通用 Schema 求值开销。
编译与回退
默认的 @CompiledValidator(fallback = false) 会在编译期拒绝不支持的 Schema 结构。如果需要把这些检查交给 Runtime SchemaPlan,可以显式启用回退:
@CompiledValidator(fallback = true)
interface UserDiagnostics {
@ValidJsonSchema(ref = "classpath:/schemas/user.json")
ValidationResult validate(User user);
}Compiled 方法接受一个待校验值,并可额外接受 boolean strictFormat 参数。返回类型决定执行行为:
| 返回类型 | 行为 |
|---|---|
boolean | 失败即停止并返回布尔结果 |
void | 校验失败时抛出异常 |
ValidationResult | 通过 Runtime fallback 返回详细结果;要求 fallback = true |
常见的类型、对象、数组、字符串、数字和组合规则可以直接编译。部分组合,包括跨 Schema 的复杂 unevaluated* 跟踪,仍需要 fallback。
各关键字的覆盖情况、限制和生成行为参阅 CompiledValidator 参考文档。
在接口中声明自定义 ValueCodec、ExternalNode 和 RegexEngine 字段。扩展作用域与回退规则参阅 Compiled APIs。
Schema 引用
SJF4J 支持 $ref、$defs、锚点及外部 Schema 引用。创建 Runtime SchemaPlan 前,可先使用 SchemaRegistry 注册外部文档:
SchemaRegistry registry = new SchemaRegistry();
registry.index(
URI.create("https://example.org/common"),
JsonSchema.fromJson("{\"type\":\"string\"}")
);
SchemaPlan plan = JsonSchema.fromJson(
"{\"$ref\":\"https://example.org/common\"}"
).formulate(registry);对于基于注解或 Compiled 的校验,@ValidJsonSchema 还支持 externalSchemas(内联映射)和 externalSchemasRef(JSON 映射文件)。例如在 @CompiledValidator 接口中:
@ValidJsonSchema(
ref = "classpath:/schemas/user.json",
externalSchemasRef = "classpath:/schemas/external.json")
boolean isValid(User user);映射文件将绝对检索 URI 与 JSON Schema 文档关联起来,供本地解析外部引用使用。SJF4J 不会自动通过 HTTP 下载远程 Schema。
对于规模较大的离线 Schema 集,可使用 externalSchemasRef 提供 URI 到 Schema 的映射文件。应将 Schema 资源纳入构建输入,让文件变更能够触发注解处理;若启用 Runtime fallback,还需确保运行时能访问映射文件。
注解式校验
@ValidJsonSchema 也可以直接标注在 Java 类型上,供 Runtime 校验使用,无须定义 Compiled 接口:
@ValidJsonSchema(ref = "classpath:/schemas/user.json")
class User {
public String name;
public int age;
}
SchemaValidator validator = new SchemaValidator();
validator.requireValid(user);SchemaValidator 会解析类型上的注解(包括带注解的父类)、缓存校验计划,并默认执行严格的 format 检查。它不同于需要显式提供 Schema 的 SchemaPlan。
在 Compiled 校验器中,@ValidJsonSchema 也可以标在方法或参数上;方法注解优先于参数和类型注解。
安全与资源限制
处理不可信的 Schema 或数据时,可以限制 Schema 规划和 Runtime 校验的资源消耗。规划与求值的数值限制默认为 0(不启用),正则 Guard 则默认开启。以下数值仅供参考。
Schema 规划限制
PlanningOptions planning = PlanningOptions.builder()
.maxSchemas(10_000)
.maxSchemaDepth(128)
.build();
SchemaRegistry registry = new SchemaRegistry(planning);
SchemaPlan plan = JsonSchema.fromJson(schemaJson).formulate(registry);| 配置项 | 限制 |
|---|---|
maxSchemas | 单次规划新建的 SchemaPlan 数量,已缓存的 Plan 不重复计数 |
maxSchemaDepth | Schema 构建深度,包含根节点 |
超出任一限制时抛出 SchemaException。这些限制适用于规划阶段,而非 JSON 解析阶段。
Runtime 校验限制
ValidationOptions options = ValidationOptions.builder()
.maxEvaluations(100_000)
.maxEvaluationDepth(128)
.maxErrors(100)
.build();
ValidationResult result = plan.validate(user, options);| 配置项 | 限制 |
|---|---|
maxEvaluations | 单次校验中 SchemaPlan 与关键字求值器的调用总次数 |
maxEvaluationDepth | Schema 求值深度,包含根节点 |
maxErrors | 达到指定的断言错误收集数量后停止校验;仅返回布尔值时不生效 |
求值预算耗尽时终止校验:validate() 返回失败结果,isValid() 返回 false,requireValid() 抛出 ValidationException。
这些配置适用于 Runtime SchemaPlan API,不直接作用于 Compiled 生成的校验代码。
正则安全
Schema 的 pattern 和 patternProperties 默认使用 Ecma262RegexEngine.DEFAULT,包含 ECMA-262 兼容转换和 RegexGuard.DEFAULT。Guard 在转换与编译前检查原始表达式。
| 防护规则 | 默认策略 |
|---|---|
| 表达式长度 | 最多 4096 个 UTF-16 code units |
| 分组嵌套深度 | 最多 32 层 |
| 数字重复次数上限 | 最多 10000,包括 {n}、{n,m} 和 {n,} |
| 嵌套无界量词 | 拒绝嵌套无界量词,例如 (a+)+ |
| 相邻无界量词 | 拒绝相同简单原子的相邻无界重复,例如 .*.* 或 a*a+ |
拒绝表达式时抛出 RegexRejectedException,而非断言失败。正则在 Runtime 规划或生成类初始化时编译;默认 Engine 的正则还会在注解处理阶段检查。匹配时不增加 Guard 检查。
WARNING
Guard 是启发式防护,可能误拒绝安全表达式,也可能漏掉高开销表达式,不能完全防御 ReDoS,也不提供匹配时的执行预算。应另外限制输入大小,对不可信正则可考虑线性时间引擎。
Guard 作用于 Schema 正则匹配关键字,不作用于 format: regex 的语法检查。
自定义正则引擎
| Engine | 正则语义 | 默认 Guard |
|---|---|---|
RegexEngine.DEFAULT | JDK | 开启 |
RegexEngine.JDK_ENGINE | JDK | 关闭 |
Ecma262RegexEngine.DEFAULT | 带 ECMA-262 兼容转换的 JDK | 开启 |
Ecma262RegexEngine.JDK_ENGINE | 带 ECMA-262 兼容转换的 JDK | 关闭 |
ECMA-262 适配层处理部分空白字符、控制字符转义和 Unicode 属性别名,并非完整实现。自定义 Engine 接收原始表达式,不会隐式转换或附加 Guard。
非法或不支持的表达式及 flags 必须抛出 RegexCompileException(保留原始异常),Schema 将其包装为 SchemaException。安全拒绝使用 RegexRejectedException;非预期错误不得转换为编译异常。
对于 Runtime 校验,在 Registry 中配置 Engine:
import org.sjf4j.schema.Ecma262RegexEngine;
import org.sjf4j.schema.PlanningOptions;
import org.sjf4j.schema.SchemaRegistry;
PlanningOptions planning = PlanningOptions.builder()
.regexEngine(Ecma262RegexEngine.JDK_ENGINE)
.build();
SchemaRegistry registry = new SchemaRegistry(planning);
SchemaPlan plan = JsonSchema.fromJson(schemaJson).formulate(registry);对于 CompiledValidator,在接口中直接声明一个静态 Engine 字段。该 Engine 同样适用于 Runtime fallback 和引用的 Schema:
@CompiledValidator
public interface UserValidator {
RegexEngine ENGINE = Ecma262RegexEngine.JDK_ENGINE;
@ValidJsonSchema("{\"pattern\":\"^[a-z]+$\"}")
boolean valid(String value);
}无 Guard 的 JDK Engine 仅用于可信正则。可通过 guardedBy(RegexGuard.DEFAULT) 附加默认 Guard,或传入自定义 RegexGuard,拒绝时必须抛出 RegexRejectedException。
示例:RE2/J。 RE2/J 提供线性时间的正则匹配。在应用中添加依赖:
implementation("com.google.re2j:re2j:1.8")public final class Re2jRegexEngine implements RegexEngine {
@Override
public Regex create(String expression, int flags) {
final com.google.re2j.Pattern pattern;
try {
pattern = com.google.re2j.Pattern.compile(
expression, translateFlags(flags));
} catch (com.google.re2j.PatternSyntaxException e) {
throw new RegexCompileException(e.getMessage(), e);
}
return new Regex() {
@Override
public boolean matches(String input) {
return pattern.matcher(input).matches();
}
@Override
public boolean find(String input) {
return pattern.matcher(input).find();
}
};
}
// See the complete example for translateFlags().
}上述配置可直接使用 new Re2jRegexEngine()。适配器转换 CASE_INSENSITIVE、MULTILINE 和 DOTALL,拒绝其他 flags。RE2/J 不支持反向引用和 lookaround,语义不同于 JDK 和 ECMA-262;不支持的语法不会回退到 JDK。
完整的 RE2/J 适配器 和集成测试 位于 Testbench。RE2/J 不是 SJF4J 的生产依赖。
标准兼容性与性能
SJF4J 支持 JSON Schema Draft 2020-12、2019-09 和 7。兼容性通过官方 JSON Schema Test Suite 测试;独立对比资源包括 Bowtie 和 Creek Service。
Runtime 校验直接作用于 Java 对象;Compiled 校验可针对稳定 Schema 生成专用实现。性能取决于 Schema 与输入对象表示。数据和测试方法参阅 JSON Schema Validation Benchmarks 及完整测试报告。
API 参考(最新发布版本): JsonSchema · SchemaPlan · @CompiledValidator · @ValidJsonSchema