commons 0.1.5
Header-only C++23 library of common/shared types for the C++ libraries
Loading...
Searching...
No Matches
json.hpp File Reference

Optional nlohmann/json integration for the Commons types. More...

#include <commons/config.hpp>
#include <commons/color.hpp>
#include <commons/display_info.hpp>
#include <commons/fixed_string.hpp>
#include <commons/flag.hpp>
#include <commons/icon.hpp>
#include <commons/id.hpp>
#include <commons/origin.hpp>
#include <commons/prioritized.hpp>
#include <commons/semver.hpp>
#include <commons/types.hpp>
#include <commons/version_constraint.hpp>
#include <nlohmann/json.hpp>
#include <array>
#include <complex>
#include <concepts>
#include <cstddef>
#include <exception>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
Include dependency graph for json.hpp:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Detailed Description

Optional nlohmann/json integration for the Commons types.

The whole body is gated behind COMMONS_WITH_NLOHMANN_JSON (see commons/config.hpp): define it, or simply have <nlohmann/json.hpp> on the include path, and these hooks light up. The header is otherwise inert.

What it adds:

  • FixedString<N> ⇄ JSON string. A string that does not fit the fixed N capacity throws on parse.
  • Color ⇄ JSON hex string (#RRGGBB, or #RRGGBBAA when not opaque). A string that does not parse throws.
  • Hsl / Hsv ⇄ JSON objects ({"h","s","l","a"} / {"h","s","v","a"}).
  • Icon ⇄ JSON **set:name string** (e.g. "mdi:abacus"). A string that does not parse throws.
  • DisplayInfo ⇄ JSON object with name/description/icon/color keys; absent (std::nullopt) fields are omitted, and icon/color reuse the Icon/Color mappings above.
  • FlagRef ⇄ JSON string (the flag name); FlagSet ⇄ JSON array of names. Reading them back resolves each name against the GlobalFlagRegistry; an unknown name throws.
  • i128 / u128 ⇄ JSON decimal string. Plain JSON numbers cannot represent 128-bit integers without loss, so they travel as strings — a genuinely useful integration rather than a silent narrowing.
  • std::optional<T> ⇄ the inner T's JSON, with nullopt ⇄ JSON null.
  • WithPriority<T> ⇄ JSON object {"priority":N,"value":<T>} and PrioritizedSet<T> ⇄ JSON array in sorted order — both only when T is itself json-serializable; the set's from_json additionally requires T's priority to be recoverable from the element.
  • Id<Tag, Repr> ⇄ the inner Repr's natural JSON (a number for the uint reprs, a string for std::string, the ULID string when ULID is also enabled).

The fixed-width builtin aliases (i8u64, f32, f64, usize, isize) need nothing here: nlohmann already serializes the underlying arithmetic types natively.