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 filen");
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: %sn", sb.GetString());
printf("Invalid keyword: %sn", l_SchemaValidator.GetInvalidSchemaKeyword());
sb.Clear();
l_SchemaValidator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
printf("Invalid document: %sn", sb.GetString());
}
else
printf("nJson file validated with the given schema successfullyn");
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用于测试。

最新更新