Я делаю физическое программное обеспечение, и мы развертываем решение json, и я хотел использовать схему json. Итак, когда у меня был неправильный ключ, типичный вид «длины» в схеме, и пользователь дает что-то неправильное, например «длина2». На самом деле я не знаю, как получить это с помощью rapidjson, я получил эти результаты
Invalid schema: #/properties/TEST
Invalid keyword: required
Invalid document: #/TEST
Но я хочу, чтобы вывод, например, ключ «длина», отсутствовал, чтобы информировать пользователя.
Имей файл test.json:
{
"$schema": "./schema.json",
"TEST": {
"Length2": {
"Value":20,
"Unit":"mm"
}
}
}
Отредактируйте следующий комментарий Ether к моей схеме.json, но это не изменит мой вывод, см. «Неверная схема».
{
"type": "object",
"required": ["TEST"],
"properties": {
"TEST": {
"type": "object",
"required": ["Length"],
"properties": {
"Length":{
"type": "object",
"required": ["Value","Unit"],
"properties": {
"Value": {"type": "number"},
"Unit": {"type": "string"}
}
}
}
}
}
}
и мой код cpp:
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
#include "rapidjson/schema.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filereadstream.h"
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
using namespace rapidjson;
int main()
{
char readBuffer[65536];
FILE* fp = fopen("test.json", "r");
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
Document d;
d.ParseStream(is);
FILE* fp2 = fopen("schema.json", "r");
FileReadStream fs(fp2, readBuffer, sizeof(readBuffer));
Document sd;
sd.ParseStream(fs);
SchemaDocument schema(sd);
SchemaValidator validator(schema);
if (!d.Accept(validator))
{
rapidjson::StringBuffer sb;
validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
printf("Invalid schema: %s\n", sb.GetString());
printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());
sb.Clear();
validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
printf("Invalid document: %s\n", sb.GetString());
}
else
printf("\nJson file validated with the given schema successfully\n");
return 0;
}
В /properties/TEST/properties
у вас должны быть имена свойств, а не схема. Возможно, вам не хватает свойства "Length"
для содержания этой подсхемы?
Итак, я нашел свой ответ, следуя примеру schemavalidator.cpp в папке rapidjson. Я привожу здесь пример в моем случае: https://github.com/faudard/rapidjson_scheme Я использую «CreateErrorMessages» так же, как в примере.