#pragma once #include namespace jsonHelper { namespace details { inline std::optional getInt(rapidjson::Value& value, const std::string& key) { // checking member exists if (!value.HasMember(key.c_str())) return std::nullopt; //getting member reference rapidjson::Value& member = value[key.c_str()]; // checking for integer if (member.IsInt() == false) return std::nullopt; // making optional with value return std::optional{member.GetInt()}; } inline std::optional getInt64(rapidjson::Value& value, const std::string& key) { // checking member exists if (!value.HasMember(key.c_str())) return std::nullopt; //getting member reference rapidjson::Value& member = value[key.c_str()]; // checking for integer if (member.IsInt64() == false) return std::nullopt; // making optional with value return std::optional{member.GetInt64()}; } inline std::optional getString(rapidjson::Value& value, const std::string& key) { // checking member exists if (!value.HasMember(key.c_str())) return std::nullopt; //getting member reference rapidjson::Value& member = value[key.c_str()]; // checking for integer if (member.IsString() == false) return std::nullopt; // making optional with value return std::string{member.GetString()}; } template inline std::optional getValue(rapidjson::Value& value, const std::string& key) { if constexpr (std::is_same_v) return getInt(value, key); else if constexpr (std::is_same_v) return getInt64(value, key); else if constexpr (std::is_same_v) return getString(value, key); else return std::nullopt; } } template inline T getValue(rapidjson::Value& value, const std::string& key) { auto ret = details::getValue(value, key); if (!ret) TraceError("JSON HELPER: FAILED TO OBTAIN VALUE BY KEY %s", key.c_str()); return ret.value_or(T{}); } inline void insertValue(rapidjson::Value& value, const std::string& key, const int& insertValue, auto&& allocator) { assert(value.IsObject()); rapidjson::Value keyValue; keyValue.SetString(key.c_str(), allocator); rapidjson::Value newValue; newValue.SetInt(insertValue); value.AddMember(keyValue, newValue, allocator); } inline void insertValue(rapidjson::Value& value, const std::string& key, const int64_t& insertValue, auto&& allocator) { assert(value.IsObject()); rapidjson::Value keyValue; keyValue.SetString(key.c_str(), allocator); rapidjson::Value newValue; newValue.SetInt64(insertValue); value.AddMember(keyValue, newValue, allocator); } inline void insertValue(rapidjson::Value& value, const std::string& key, const std::string& insertValue, auto&& allocator) { assert(value.IsObject()); rapidjson::Value keyValue; keyValue.SetString(key.c_str(), allocator); rapidjson::Value newValue; newValue.SetString(insertValue.c_str(), allocator); value.AddMember(keyValue, newValue, allocator); } }