You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中通过json-schema-validator获取JSON Schema自定义错误信息

解决方案

问题根源

你当前的问题有两个核心点:

  1. JSON Schema中使用的message字段不符合com.networknt/json-schema-validator库的自定义错误信息规范
  2. 错误信息的键名pattern与触发验证失败的关键字minLength不匹配,导致无法命中自定义信息

修正步骤

1. 修改JSON Schema的自定义错误信息配置

将原Schema中的message替换为库要求的errorMessage,并将键名改为对应验证关键字minLength:

"membershipNo": {
  "type": "string",
  "minLength": 1,
  "errorMessage": {
    "minLength": "membershipNo should not be empty"
  }
}

如果需要中文提示,直接修改值即可:

"errorMessage": {
  "minLength": "会员编号不能为空"
}

2. 调整Java代码(可选,确保自定义信息生效)

默认情况下库已开启自定义错误信息支持,若需显式确认,可在创建JsonSchemaFactory时配置ValidationConfig:

// 显式配置开启自定义错误信息
ValidationConfig validationConfig = new ValidationConfig();
validationConfig.setErrorMessageEnabled(true);

JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7, validationConfig);
JsonSchema schema = factory.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());
}

多关键字自定义信息示例

如果需要为多个验证规则设置不同的自定义提示,可在errorMessage下添加多个键值对:

"membershipNo": {
  "type": "string",
  "minLength": 1,
  "pattern": "^[A-Z0-9]+$",
  "errorMessage": {
    "minLength": "会员编号不能为空",
    "type": "会员编号必须为字符串类型",
    "pattern": "会员编号只能包含大写字母和数字"
  }
}

内容的提问来源于stack exchange,提问作者Loren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:36:21