json-schema-validator/example/format.cpp
Cristian Le 0d60d48a58
Modernize cmake script (#262)
* Remove travis file
* Apply pre-commit fixes
* Modernize cmake file

- Added JSON_VALIDATOR_SHARED_LIBS to properly handle shared-library
- Bumped minimum cmake to 3.11 to use no-source add_library
- Bumped minimum cmake to 3.14 to properly support FetchContent (FetchContent_MakeAvailable)
- Converted Hunter package manager to FetchContent (It is plenty mature these days)
- Added namespace to exported target
- Made the cmake file compatible with FetchContent

* Use simplified FetchContent CI
* Add simple status messages
* Handle nlohmann dependency

Not an ideal approach, but required in order for the exported target to have appropriate linkage.
Maybe this can be designed to become a PRIVATE link library, but then how does it ensure the target is installed?

* Remove CMake-install test

This will be moved to packaging integration tests

* Enable code coverage

* Reconfigure ci presets

Signed-off-by: Cristian Le <cristian.le@mpsd.mpg.de>
2023-05-11 12:07:56 +02:00

55 lines
1.3 KiB
C++

#include <iostream>
#include <nlohmann/json-schema.hpp>
using nlohmann::json;
using nlohmann::json_schema::json_validator;
// The schema is defined based upon a string literal
static json uri_schema = R"(
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"myUri": {
"type":"string",
"format": "uri"
}
}
})"_json;
// The people are defined with brace initialization
static json good_uri = {{"myUri", "http://hostname.com/"}};
static json bad_uri = {{"myUri", "http:/hostname.com/"}};
static void uri_format_checker(const std::string &format, const std::string &value)
{
if (format == "uri") {
if (value.find("://") == std::string::npos)
throw std::invalid_argument("URI does not contain :// - invalid");
} else
throw std::logic_error("Don't know how to validate " + format);
}
int main()
{
json_validator validator(nullptr, uri_format_checker); // create validator
try {
validator.set_root_schema(uri_schema); // insert root-schema
} catch (const std::exception &e) {
std::cerr << "Validation of schema failed, here is why: " << e.what() << "\n";
return EXIT_FAILURE;
}
validator.validate(good_uri);
try {
validator.validate(bad_uri);
} catch (const std::exception &e) {
std::cerr << "Validation expectedly failed, here is why: " << e.what() << "\n";
}
return EXIT_SUCCESS;
}