core-adapters 0.1.3
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
json.hpp File Reference

snicholls::json_error and the nlohmann/json adapter layer: shared by every adapter. More...

#include <stdexcept>
#include <string>
#include <string_view>
#include <nlohmann/json.hpp>

Go to the source code of this file.

Classes

struct  snicholls::json_error
 A JSON value that does not convert to or from a core type. More...
 

Detailed Description

snicholls::json_error and the nlohmann/json adapter layer: shared by every adapter.

Overview
snicholls-core is standard-library-only and stays so. Its value types still need a JSON form, and the snicholls libraries that speak JSON use nlohmann/json, so the JSON hooks live in this repository, under include/snicholls/core_adapters/nlohmann/, behind their own CMake target snicholls::core_json.

Include the adapter for the type you serialise - time_json.hpp, uuid_json.hpp, decimal_json.hpp, secret_json.hpp - and nlohmann::json j = value; / j.get<T>() work through argument-dependent lookup. This header is what they share: the error type and the rule that no nlohmann exception escapes an adapter.

Relationships
Guarantees and contracts
  • Errors are translated at the boundary: an adapter's from_json throws snicholls::json_error, never a nlohmann::json::exception. Tests prove it for every adapter and every kind of JSON value.
  • No implicit conversions: the vendored nlohmann/json is built with JSON_ImplicitConversions=OFF; convert with j.get<T>(). The adapters do not depend on the setting.
Errors
snicholls::json_error (a std::runtime_error), with a message naming the type and quoting at most 64 characters of the offending text (never for secret, whose text is never quoted).
Examples
const nlohmann::json j = nlohmann::json::parse(R"({"id": 42})");
try {
const auto id = j.at("id").get<snicholls::uuid>(); // a number where a UUID string belongs
static_cast<void>(id);
} catch (const snicholls::json_error& e) { // never a nlohmann::json::exception
std::printf("refused: %s\n", e.what());
}
A JSON value that does not convert to or from a core type.
Definition json.hpp:76
Performance
Not benchmarked: each hook is the core text function plus one std::string assignment.
Tests and demos
  • Tests: tests/nlohmann/json_test.cpp.
  • Demo: demos/nlohmann/json_demo.cpp.
Dependencies
CMake target snicholls::core_json (= snicholls::core + nlohmann_json::nlohmann_json, the vendored third_party/nlohmann_json at v3.12.0 unless the consumer already defines that target). Enabled by CORE_ADAPTERS_WITH_NLOHMANN (ON by default).
Known issues and gotchas
  • snicholls::core_json is not installed: consume it from the source tree (add_subdirectory).
Status
Experimental, pre-1.0.

Definition in file json.hpp.