【发布时间】:2018-11-21 14:06:40
【问题描述】:
我期待 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
【问题讨论】:
-
感谢您的提问。你能在你的代码之外提供你的 JSON Schema 和 JSON 实例吗?这使我们可以首先检查架构本身是否存在问题。谢谢。
-
Json 文件已经在代码之外。只需从 g_plJsonSchema 中删除反斜杠即可获取架构。
-
{"$schema": "json-schema.org/draft-04/schema#", "title": "Schema", "description": "用于验证 Json 文件的 JSON 模式", "type": "object", "属性”:{“MAX_CONNECTION_PER_HOST”:{“类型”:“数字”},“QUEUE_IO_SIZE”:{“类型”:“数字”},“REQUEST_LOW_WATER_MARK”:{“类型”:“数字”},“必需”: [“MAX_CONNECTION_PER_HOST”、“QUEUE_IO_SIZE”、“REQUEST_LOW_WATER_MARK”] } }
-
我只是希望我在删除反斜杠时没有犯任何错误。
-
为了将来参考,最好编辑您的问题以添加代码块而不是使用 cmets,但是,这可以使用 =]
标签: jsonschema rapidjson