如果验证失败,我将在java代码中访问json模式中的自定义错误消息集。但我拿不来。你能帮我找个办法吗?
图书馆插件
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.0.49</version>
</dependency>Json-模式
"membershipNo": {
"type": "string",
"minLength": 1,
"message": {
"pattern": "membershipNo should not be empty"
}
}我就是这样获取Java类中的错误的-
JsonSchema schema = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7).getSchema(schemaAsStream);
ObjectMapper om = new ObjectMapper();
om.setPropertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE);
JsonNode jsonNode = om.readTree(payload);
Set<ValidationMessage> errors = schema.validate(jsonNode);
for (ValidationMessage error : errors) {
System.out.println(error.getMessage());
}
Error Getting- $.payment.membershipNo: must be at least 1 characters long"
Error Expected - membershipNo should not be empty 发布于 2022-08-11 10:07:32
根据文档,您可以在json模式本身中提供自定义消息,但不能以您的方式提供。
例如,如果您有这样的JSON模式(带有默认消息):
{
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"foo": {
"type": "array",
"maxItems": 3
}
}
}您可以通过更改上面的JSON模式来定制错误消息,如下所示:
{
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"foo": {
"type": "array",
"maxItems": 3
}
},
"message": {
"maxItems" : "MaxItem must be 3 only",
"type" : "Invalid type"
}
}在消息字段中,用户可以声明他们的自定义消息。键应该是验证类型,值应该是自定义消息。
"message": {
[validationType] : [customMessage]
}此外,我们还可以使用从ValidationMessage.java类返回的属性(如参数、路径e.t.c )对动态消息进行格式化。
看一看按下
通过这个设置,这一行代码:
for (ValidationMessage error : errors) {
System.out.println(error.getMessage());
}应该打印您的自定义错误消息。
https://stackoverflow.com/questions/73305460
复制相似问题