From b554b91ec0b0f5087db8f22d4d1c19d5c7b07246 Mon Sep 17 00:00:00 2001 From: Riyyi Date: Fri, 5 Feb 2021 01:09:43 +0100 Subject: [PATCH] Add json utility class --- inferno/src/inferno/util/json.h | 64 +++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 inferno/src/inferno/util/json.h diff --git a/inferno/src/inferno/util/json.h b/inferno/src/inferno/util/json.h new file mode 100644 index 0000000..967d045 --- /dev/null +++ b/inferno/src/inferno/util/json.h @@ -0,0 +1,64 @@ +#ifndef JSON_UTIL_H +#define JSON_UTIL_H + +#include // std::optional + +#include "nlohmann/json.hpp" + +#include "inferno/assert.h" + +namespace Inferno { + + using json = nlohmann::json; + using json_const_iterator = nlohmann::json::const_iterator; + + class Json { + public: + static const json& getValue(json_const_iterator& it) + { + return it.value(); + } + + template + static std::optional getType(const json& json, C check) + { + if (json.type() == check) { + return json.get(); + } + + return {}; + } + + // --------------------------------- + + static bool hasProperty(const json& json, json_const_iterator& it, const char* member) + { + it = json.find(member); + return it != json.end(); + } + + // --------------------------------- + + template + static std::optional parseProperty(const json& json, const char* property, bool required, C check) + { + bool result; + json_const_iterator it; + + // Has property + result = hasProperty(json, it, property); + ASSERT(!required || (required && result), "Json could not find property '{}'", property); + + if (!result) { + return {}; + } + + // Return data found in iterator, empty if incorrect type + return getType(getValue(it), check); + } + }; + +} // namespace Inferno + + +#endif // JSON_UTIL_H