MQTTSuite
Loading...
Searching...
No Matches
format.cpp
Go to the documentation of this file.
1#include <iostream>
2
3#include <nlohmann/json-schema.hpp>
4
5using nlohmann::json;
6using nlohmann::json_schema::json_validator;
7
8// The schema is defined based upon a string literal
9static json uri_schema = R"(
10{
11 "$schema": "http://json-schema.org/draft-07/schema#",
12 "type": "object",
13 "properties": {
14 "myUri": {
15 "type":"string",
16 "format": "uri"
17 }
18 }
19})"_json;
20
21// The people are defined with brace initialization
22static json good_uri = {{"myUri", "http://hostname.com/"}};
23static json bad_uri = {{"myUri", "http:/hostname.com/"}};
24
25static void uri_format_checker(const std::string &format, const std::string &value)
26{
27 if (format == "uri") {
28 if (value.find("://") == std::string::npos)
29 throw std::invalid_argument("URI does not contain :// - invalid");
30 } else
31 throw std::logic_error("Don't know how to validate " + format);
32}
33
34int main()
35{
36 json_validator validator(nullptr, uri_format_checker); // create validator
37
38 try {
39 validator.set_root_schema(uri_schema); // insert root-schema
40 } catch (const std::exception &e) {
41 std::cerr << "Validation of schema failed, here is why: " << e.what() << "\n";
42 return EXIT_FAILURE;
43 }
44
45 validator.validate(good_uri);
46
47 try {
48 validator.validate(bad_uri);
49 } catch (const std::exception &e) {
50 std::cerr << "Validation expectedly failed, here is why: " << e.what() << "\n";
51 }
52
53 return EXIT_SUCCESS;
54}
json_validator(schema_loader=nullptr, format_checker=nullptr, content_checker=nullptr)
static json uri_schema
Definition format.cpp:9
static json bad_uri
Definition format.cpp:23
static json good_uri
Definition format.cpp:22
static void uri_format_checker(const std::string &format, const std::string &value)
Definition format.cpp:25
int main()
Definition format.cpp:34