入参校验产品化 schema_个人渣记录仅为自己搜索用的博客-CSDN博客
自定义的string format可以使用. 详见
fpe的 addFormatValidator
ajv 的 addFormat能力
借鉴自chatgpt , 谷歌了半天没答案.
Q: "networknt JsonSchemaFactory Keyword "
A: 如下
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.0.76</version> // 2023年
</dependency>
static String schema = "{\n"
+ " \"$ref\": \"#/definitions/Welcome\",\n"
+ " \"definitions\": {\n"
+ " \"Welcome\": {\n"
+ " \"type\": \"object\",\n"
+ " \"additionalProperties\": false,\n"
+ " \"properties\": {\n"
+ " \"timePartition\": {\n"
+ " \"groovy\": 131,\n"
+ " \"type\": \"string\""
+ " }\n"
+ " },\n"
+ "
+ " \"title\": \"Welcome\"\n"
+ " }
+ " }\n"
+ "}\n";
static String requestJson = "{\n"
+ " \"timePartition\": \"2023-02-08 19:30:00\"\n"
+ "}";
protected static JsonSchema getJsonSchemaFromJsonNodeVer(JsonNode jsonNode, SpecVersion.VersionFlag versionFlag) {
JsonSchemaVersion jsonSchemaVersion = JsonSchemaFactory.checkVersion(versionFlag);
JsonMetaSchema metaSchema = jsonSchemaVersion.getInstance();
GroovyKeyword value = new GroovyKeyword();
metaSchema.getKeywords().put(value.getValue(), value);
JsonSchemaFactory factory= JsonSchemaFactory.builder().defaultMetaSchemaURI(metaSchema.getUri()).addMetaSchema(metaSchema).build();
return factory.getSchema(jsonNode);
}
public static class GroovyKeyword extends AbstractKeyword {
private final Logger logger = LoggerFactory.getLogger(GroovyKeyword.class);
public GroovyKeyword() {
super("groovy");
}
@Override
public AbstractJsonValidator newValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) throws
JsonSchemaException, Exception {
System.out.println("GroovyKeyword_schemaPath:"+schemaPath+",schemaNodeValue:"+schemaNode+" parentSchemaNodeKv:"+ parentSchema+",validationContext="+validationContext);
String config = schemaNode.asText();
AbstractJsonValidator abstractJsonValidator = new AbstractJsonValidator() {
@Override
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
System.out.println("GroovyKeyword.validate_config:"+config+",path:"+at+",node:"+ node);
System.out.println("GroovyKeyword.validate_rootNode="+rootNode);
return Collections.emptySet();
}
};
return abstractJsonValidator;
}
}
GroovyKeyword_schemaPath:#/definitions/Welcome/properties/timePartition,schemaNodeValue:131 parentSchemaNodeKv:"#/definitions/Welcome/properties/timePartition" : {"groovy":131,"type":"string"},validationContext=com.networknt.schema.ValidationContext@205d38da
GroovyKeyword.validate_config:131 ,path:$.timePartition, node:"2023-02-08 19:30:00"
GroovyKeyword.validate_rootNode={"timePartition":"2023-02-08 19:30:00"}
validate_time=6