JSON Schema

JSON Schema 作为数据交换领域的标准化工具,能够通过预定义规则约束 JSON 数据的结构与属性。其验证器通过自动化校验机制确保数据合规性;

JSON Schema 用来定义json 数据结构的属性,JSON Schema 验证器,则是根据JSON Schema的定义来检查json数据属性和结构是否符合Schema定义。
架构图

Spring Boot 项目的完整集成

依赖配置

采用 networknt 提供的验证器实现,需在 pom.xml 添加以下依赖:

<dependency>
  <groupId>com.networknt</groupId>
  <artifactId>json-schema-validator</artifactId>
  <version>1.4.0</version>
</dependency>
Schema 定义示例

订单事件的 Schema 定义包含字段类型约束、枚举值限制及嵌套结构验证:

{
  "$schema" : "http://json-schema.org/draft-07/schema#",
  "type" : "object",
  "properties" : {
    "createTime" : {
      "type" : "integer"
    },
    "dataId" : {
      "type" : "string"
    },
    "id" : {
      "type" : "integer"
    },
    "modifyTime" : {
      "type" : "integer"
    },
    "script" : {
      "type" : "string"
    },
    "url" : {
      "type" : "string"
    }
  },
  "required" : [ "createTime", "dataId", "id", "modifyTime", "script", "url" ]
}
动态生成 Schema

通过 Java 类自动生成 Schema 可提升维护效率:

SchemaGeneratorConfigBuilder configBuilder =
            new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_7, OptionPreset.PLAIN_JSON);

        configBuilder.forFields()
            .withNullableCheck(field -> field.getAnnotationConsideringFieldAndGetter(Nullable.class) != null);
        configBuilder.forFields()
            .withRequiredCheck(field -> field.getAnnotationConsideringFieldAndGetter(Nullable.class) == null);
        configBuilder.forMethods()
            .withRequiredCheck(method -> method.getAnnotationConsideringFieldAndGetter(NotNull.class) != null);

        SchemaGeneratorConfig config = configBuilder
            .with(new JavaxValidationModule())
            .with(new JacksonModule())
            .build();

        SchemaGenerator generator = new SchemaGenerator(config);
        JsonNode jsonSchema = generator.generateSchema(TrackingParserCOMessage.class);

        System.out.println(jsonSchema.toPrettyString());
校验服务实现

注入校验器并封装校验逻辑:

@Service
public class SchemaValidator {
    @Autowired 
    private JsonSchema schema;

    public String validate(JsonNode data) {
        Set<ValidationMessage> valid = schema.validate(data);
        return errors.isEmpty() ? "Valid" : errors.toString();
    }
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐