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

Java中JSON Schema数组元素不匹配模式时验证未报错问题排查

JSON数组元素Schema验证失效问题解决

问题场景

在Java 17环境下,使用com.fasterxml.jackson.core和com.networknt:json-schema-validator库验证JSON字符串时,发现数组中不符合Schema规则的元素未触发错误提示。预期数组元素必须是13位数字字符串,但输入中前两个元素不符合规则的情况下,验证结果未检测到错误,而同类验证逻辑可正常识别错误。

测试用例

JSON输入(仅最后一个元素符合要求):

{
    "mylist": ["123Abc", "123456789012", "1234567890123"]
}

JSON Schema:

{
    "$id" : "https://schema.mysite.se/myschema",
    "$schema" : "https://json-schema.org/draft/2020-12/schema",
    "type" : "object",
    "properties" : {
        "mylist" : {
            "type" : "array",
            "items" : {
                "type" : "string",
                "pattern" : "^[0-9]{13}$"
            },
            "minItems" : 1,
            "uniqueItems" : true
        }
    }
}

Java验证代码:

ObjectMapper mapper = new ObjectMapper();
JsonSchemaFactory schemaFactory = 
JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
JsonNode node = mapper.readTree(jsonData);
JsonSchema schema = schemaFactory.getSchema(inputSchema);
Set<ValidationMessage> validationResult = schema.validate(node);

assertEquals(2, validationResult.size()); // 预期检测到2个错误,实际为0

问题原因

使用的com.networknt:json-schema-validator版本为1.0.76,该版本存在数组元素模式验证的Bug,导致不符合规则的元素无法被检测到。

解决方案

将com.networknt:json-schema-validator升级至1.4.0版本,升级后验证逻辑可正常触发错误提示,符合预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:12:12