jsonschema - 即使缺少必填字段,Rapidjson 也会成功验证
问题描述
我期待 rapidjson 给出验证错误,因为我的 json 文件不包含架构中提到的“必需”字段之一。但是,由于某些原因,这不会发生。
dbconf.json(json 文件)
{
"MAX_CONNECTION_PER_HOST":20,
"QUEUE_IO_SIZE":10485,
"Garbage":50000
}
这是测试代码和架构。
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
#include "rapidjson/schema.h"
#include <rapidjson/stringbuffer.h>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
const char g_plJsonSchema[]="{\
\"$schema\": \"http://json-schema.org/draft-04/schema#\",\
\"title\": \"Schema\",\
\"description\": \"JSON schema for validating Json file\",\
\"type\": \"object\",\
\"properties\": {\
\"MAX_CONNECTION_PER_HOST\": { \"type\": \"number\" },\
\"QUEUE_IO_SIZE\": { \"type\": \"number\" },\
\"REQUEST_LOW_WATER_MARK\": { \"type\": \"number\" },\
\"required\": [\
\"MAX_CONNECTION_PER_HOST\",\
\"QUEUE_IO_SIZE\",\
\"REQUEST_LOW_WATER_MARK\"\
]\
}\
}";
int main()
{
rapidjson::Document l_peerAddSchemaDoc, l_peerAddDataDoc;
l_peerAddSchemaDoc.Parse(g_plJsonSchema);
if(l_peerAddSchemaDoc.HasParseError())
{
printf("JSON schema file is not a valid JSON file\n");
return -1;
}
std::ifstream l_confDataIStream("dbconf.json");
std::string l_confDataIStreamStr((std::istreambuf_iterator<char>(l_confDataIStream)),(std::istreambuf_iterator<char>()));
l_peerAddDataDoc.Parse(l_confDataIStreamStr.c_str());
rapidjson::SchemaDocument l_schemaDocument(l_peerAddSchemaDoc);
rapidjson::SchemaValidator l_SchemaValidator(l_schemaDocument);
if(!l_peerAddDataDoc.Accept(l_SchemaValidator))
{
rapidjson::StringBuffer sb;
l_SchemaValidator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
printf("Invalid schema: %s\n", sb.GetString());
printf("Invalid keyword: %s\n", l_SchemaValidator.GetInvalidSchemaKeyword());
sb.Clear();
l_SchemaValidator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
printf("Invalid document: %s\n", sb.GetString());
}
else
printf("\nJson file validated with the given schema successfully\n");
return 0;
}
我得到以下输出
Json file validated with the given schema successfully
解决方案
您的问题required
应该是在根级别,而不是在properties
. 实际上,您当前的架构无效,因为里面的所有键值properties
都应该只是对象。
{
"$schema": "json-schema.org/draft-04/schema#",
"title": "Schema",
"description": "JSON schema for validating Json file",
"type": "object",
"properties": {
"MAX_CONNECTION_PER_HOST": {
"type": "number"
},
"QUEUE_IO_SIZE": {
"type": "number"
},
"REQUEST_LOW_WATER_MARK": {
"type": "number"
}
},
"required": [
"MAX_CONNECTION_PER_HOST",
"QUEUE_IO_SIZE",
"REQUEST_LOW_WATER_MARK"
]
}
我使用https://www.jsonschemavalidator.net针对实例验证了架构以进行测试。
推荐阅读
- webpack - 将 webpack 块图导出到 json
- java - 为什么它说我缺少括号?
- php - 尝试使用 PHP 和 SQL 为我的游戏制作 hiscore 排行榜
- javascript - 如果用户在聊天室中,则突出显示 ping,Javascript
- php - ¿ 我可以在 Mysql 中设置同时使用两个不同的数据库吗?
- java - 为什么我的图片没有被添加?JavaSwing
- mpi - Slurm MPI 错误:ORTE 守护程序失败
- python - 如何在 GPU 上处理字符串操作?
- progressive-web-apps - 新的更新可用消息和发布操作
- node.js - 超测附件:不支持的媒体类型:multipart/form-data;