CoriEngine
Loading...
Searching...
No Matches
JsonSerializer.hpp
Go to the documentation of this file.
1#pragma once
2#include <nlohmann/json.hpp>
3
4namespace Cori {
5 namespace FileSystem {
9 template<typename T>
10 concept JsonSerializable = requires(T value, const nlohmann::json j) {
11 { nlohmann::json(value) } -> std::same_as<nlohmann::json>;
12 { j.get<T>() } -> std::same_as<T>;
13 };
14
19 public:
27 template<JsonSerializable T>
28 static std::expected<void, Core::CoriError<>> Save(const T& data, const std::filesystem::path& filepath) {
29 try {
30
31 const auto parent_dir = filepath.parent_path();
32
33 if (!parent_dir.empty()) {
34 std::filesystem::create_directories(parent_dir);
35 }
36
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())));
40 }
41
42
43 nlohmann::json j = data;
44 file << std::fixed << std::setprecision(4);
45 file << j.dump(4);
46
47 return {};
48 }
49 catch (const std::exception& e) {
50 return std::unexpected(Core::CoriError(std::format("An unexpected error occurred during save: ", e.what())));
51 }
52 }
53
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())));
64 }
65
66 try {
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())));
70 }
71
72 nlohmann::json j;
73 file >> j;
74 return j.get<T>();
75 }
76 catch (const nlohmann::json::exception& e) {
77 return std::unexpected(Core::CoriError(std::format("JSON processing error: ", e.what())));
78 }
79 catch (const std::exception& e) {
80 return std::unexpected(Core::CoriError(std::format("An unexpected error occurred during load: ", e.what())));
81 }
82 }
83 };
84 }
85}
Custom error class mainly used in std::expected.
Definition Error.hpp:27
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.
Global engine namespace.