Xiangiqgame
AI engine for Xiangqi
Loading...
Searching...
No Matches
json_schema_validate.cpp
Go to the documentation of this file.
1
3
4#include <iostream>
5#include <iomanip>
6
7#include <nlohmann/json-schema.hpp>
8
9using nlohmann::json;
10using nlohmann::json_schema::json_validator;
11
12// The schema is defined based upon a string literal
13static json person_schema = R"(
14{
15 "$schema": "http://json-schema.org/draft-07/schema#",
16 "title": "A person",
17 "properties": {
18 "name": {
19 "description": "Name",
20 "type": "string"
21 },
22 "age": {
23 "description": "Age of the person",
24 "type": "number",
25 "minimum": 2,
26 "maximum": 200
27 }
28 },
29 "required": [
30 "name",
31 "age"
32 ],
33 "type": "object"
34}
35
36)"_json;
37
38// The people are defined with brace initialization
39static json bad_person = {{"age", 42}};
40static json good_person = {{"name", "Albert"}, {"age", 42}};
41
42int main()
43{
44 /* json-parse the schema */
45
46 json_validator validator; // create validator
47
48 try {
49 validator.set_root_schema(person_schema); // insert root-schema
50 } catch (const std::exception &e) {
51 std::cerr << "Validation of schema failed, here is why: " << e.what() << "\n";
52 return EXIT_FAILURE;
53 }
54
55 /* json-parse the people - API of 1.0.0, default throwing error handler */
56
57 for (auto &person : {bad_person, good_person}) {
58 std::cout << "About to validate this person:\n"
59 << std::setw(2) << person << std::endl;
60 try {
61 validator.validate(person); // validate the document - uses the default throwing error-handler
62 std::cout << "Validation succeeded\n";
63 } catch (const std::exception &e) {
64 std::cerr << "Validation failed, here is why: " << e.what() << "\n";
65 }
66 }
67
68 /* json-parse the people - with custom error handler */
69 // class custom_error_handler : public nlohmann::json_schema::basic_error_handler
70 // {
71 // void error(const nlohmann::json_pointer<nlohmann::basic_json<>> &pointer, const json &instance,
72 // const std::string &message) override
73 // {
74 // nlohmann::json_schema::basic_error_handler::error(pointer, instance, message);
75 // std::cerr << "ERROR: '" << pointer << "' - '" << instance << "': " << message << "\n";
76 // }
77 // };
78
79
80 // for (auto &person : {bad_person, good_person}) {
81 // std::cout << "About to validate this person:\n"
82 // << std::setw(2) << person << std::endl;
83
84 // custom_error_handler err;
85 // validator.validate(person, err); // validate the document
86
87 // if (err)
88 // std::cerr << "Validation failed\n";
89 // else
90 // std::cout << "Validation succeeded\n";
91 // }
92
93 return EXIT_SUCCESS;
94}
static json person_schema
static json good_person
static json bad_person
int main()