2#include <nlohmann/json.hpp>
11 { nlohmann::json(value) } -> std::same_as<nlohmann::json>;
12 { j.get<T>() } -> std::same_as<T>;
27 template<JsonSerializable T>
28 static std::expected<void, Core::CoriError<>>
Save(
const T& data,
const std::filesystem::path& filepath) {
31 const auto parent_dir = filepath.parent_path();
33 if (!parent_dir.empty()) {
34 std::filesystem::create_directories(parent_dir);
37 std::ofstream file(filepath);
38 if (!file.is_open()) {
39 return std::unexpected(
Core::CoriError(std::format(
"Could not open file for writing: ", filepath.string())));
43 nlohmann::json j = data;
44 file << std::fixed << std::setprecision(4);
49 catch (
const std::exception& e) {
50 return std::unexpected(
Core::CoriError(std::format(
"An unexpected error occurred during save: ", e.what())));
60 template<JsonSerializable T>
61 static std::expected<T, Core::CoriError<>>
Load(
const std::filesystem::path& filepath) {
62 if (!std::filesystem::exists(filepath)) {
63 return std::unexpected(
Core::CoriError(std::format(
"File does not exist: ", filepath.string())));
67 std::ifstream file(filepath);
68 if (!file.is_open()) {
69 return std::unexpected(
Core::CoriError(std::format(
"Could not open file for reading: ", filepath.string())));
76 catch (
const nlohmann::json::exception& e) {
77 return std::unexpected(
Core::CoriError(std::format(
"JSON processing error: ", e.what())));
79 catch (
const std::exception& e) {
80 return std::unexpected(
Core::CoriError(std::format(
"An unexpected error occurred during load: ", e.what())));
Custom error class mainly used in std::expected.
Class is responsible for simple loading/saving config and save files as json files.
static std::expected< void, Core::CoriError<> > Save(const T &data, const std::filesystem::path &filepath)
Saves a serializable object to a JSON file.
static std::expected< T, Core::CoriError<> > Load(const std::filesystem::path &filepath)
Loads an object from a JSON file.
To satisfy use NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE macro. Refer here https://json.nlohmann....
Everything connected to interacting with files and filesystem is in this namespace.