JSON Schema验证是否支持自定义错误消息?Newtonsoft验证问题求助
Newtonsoft JSON Schema自定义错误消息问题
待验证的JSON对象
{ "json": { "is_expanded_identification": false, "identity": { "concat_id": 44446543R, "concat_id_type_code": 1 } } , "study_year": "2025" }
使用的JSON Schema
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": [ "json", "study_year" ], "properties": { "json": { "type": "object", "required": [ "is_expanded_identification", "identity" ], "properties": { "is_expanded_identification": { "type": "boolean" }, "identity": { "type": "object", "required": [ "concat_id", "concat_id_type_code" ], "properties": { "concat_id": { "type": "integer", "errorMessage": { "type": "My custom messsage" } }, "concat_id_type_code": { "type": "integer" } } } } }, "study_year": { "type": "string", "pattern": "^\\d{4}$" } } }
问题描述
由于concat_id字段值44446543R包含字母R,我期望触发Schema中定义的自定义错误消息,但实际返回Newtonsoft默认错误:Unexpected character encountered while parsing number: R.。尝试使用errorMessage和message字段均无效,想问Newtonsoft的JSON Schema验证是否支持自定义错误消息?
解答
核心原因:解析错误发生在Schema验证之前
Newtonsoft执行JSON Schema验证的前提是输入的JSON能被成功解析为JToken对象。你的44446543R不是合法的JSON数值(JSON数值不允许包含字母),所以在解析阶段就直接抛出了错误,根本没进入Schema验证流程,自然不会触发Schema里定义的自定义错误消息。Newtonsoft JSON Schema对自定义错误消息的支持
Newtonsoft的JSON Schema本身支持自定义错误消息,但需要使用其扩展的关键字(比如errorMessage,需确保使用的版本支持该扩展),且必须保证JSON能被正常解析,才能让Schema验证逻辑生效。解决办法
- 若
concat_id允许包含字母,需调整Schema和JSON格式:- 将Schema中
concat_id的type改为string,并添加pattern规则(比如"pattern": "^\\d+R$")来匹配目标格式; - 将JSON中的
44446543R改为字符串形式,即"concat_id": "44446543R"。这样JSON能正常解析,当值不符合Schema规则时,就会触发自定义错误消息。
- 将Schema中
- 若必须保持当前JSON的写法(不加引号),则这属于无效JSON,只能在解析阶段捕获错误并自定义提示,无法通过Schema验证来控制错误消息。
内容的提问来源于stack exchange,提问作者leah
相关产品推荐
相关产品推荐

