CheatMenuSA/src/Json.h

124 lines
1.9 KiB
C
Raw Normal View History

2020-12-02 16:19:16 -05:00
#pragma once
2021-04-07 16:35:21 -04:00
#include "../Depend/json.hpp"
2020-12-02 16:19:16 -05:00
/*
Wrapper class for nlohmann::json
Contains helper methods
*/
2020-12-02 16:19:16 -05:00
class CJson
{
private:
2021-06-18 12:49:11 -04:00
std::string m_FilePath;
2020-12-02 16:19:16 -05:00
public:
2021-06-18 12:49:11 -04:00
nlohmann::json m_Data;
/*
2021-02-24 16:54:45 -05:00
Returns a value from json structure hierarchy using '.'
Example: "Menu.Window.X"
*/
// specialize since typeid(std::string) doesn't work
2020-12-02 16:19:16 -05:00
template <typename T>
2021-06-18 12:49:11 -04:00
T GetValue(std::string&& key, T&& defaultVal)
2020-12-02 16:19:16 -05:00
{
2021-06-18 12:49:11 -04:00
try
{
2020-12-02 16:19:16 -05:00
std::stringstream ss(key);
std::string line;
2021-06-18 12:49:11 -04:00
nlohmann::json* json = &m_Data;
2020-12-02 16:19:16 -05:00
while (getline(ss, line, '.'))
{
2020-12-02 16:19:16 -05:00
json = &((*json)[line]);
}
2021-02-24 16:54:45 -05:00
2020-12-02 16:19:16 -05:00
// json library bugs with bool, using int instead
if (typeid(T) == typeid(bool))
{
return ((json->get<int>() == 1) ? true : false);
}
2021-06-18 12:49:11 -04:00
return json->get<T>();
2020-12-02 16:19:16 -05:00
}
2021-06-18 12:49:11 -04:00
catch (...)
{
return defaultVal;
2020-12-02 16:19:16 -05:00
}
}
2021-02-24 16:54:45 -05:00
2021-06-18 12:49:11 -04:00
template <>
std::string GetValue(std::string&& key, std::string&& defaultVal)
{
2021-06-18 12:49:11 -04:00
try
{
std::stringstream ss(key);
std::string line;
2021-06-18 12:49:11 -04:00
nlohmann::json* json = &m_Data;
while (getline(ss, line, '.'))
{
json = &((*json)[line]);
}
return json->get<std::string>();
}
2021-06-18 12:49:11 -04:00
catch (...)
{
return defaultVal;
}
}
/*
2021-02-24 16:54:45 -05:00
Allows to save values in json hierarchy using '.'
Example: "Menu.Window.X"
*/
2020-12-02 16:19:16 -05:00
template <typename T>
void SetValue(std::string&& key, T& val)
2020-12-02 16:19:16 -05:00
{
std::stringstream ss(key);
std::string line;
2021-06-18 12:49:11 -04:00
nlohmann::json* json = &m_Data;
2020-12-02 16:19:16 -05:00
while (getline(ss, line, '.'))
{
2020-12-02 16:19:16 -05:00
json = &((*json)[line]);
}
2020-12-02 16:19:16 -05:00
// json library bugs with bool, using int instead
if (typeid(T) == typeid(bool))
{
2020-12-02 16:19:16 -05:00
*json = (val ? 1 : 0);
}
2020-12-02 16:19:16 -05:00
else
{
2020-12-02 16:19:16 -05:00
*json = val;
}
2020-12-02 16:19:16 -05:00
}
2021-06-18 12:49:11 -04:00
template <>
void SetValue(std::string&& key, std::string& val)
{
std::stringstream ss(key);
std::string line;
2021-06-18 12:49:11 -04:00
nlohmann::json* json = &m_Data;
while (getline(ss, line, '.'))
{
json = &((*json)[line]);
}
*json = val;
}
2021-06-18 12:49:11 -04:00
/*
Saves json data to disk
*/
void WriteToDisk();
2021-06-17 09:00:32 -04:00
CJson(const char* text = "");
2020-12-02 16:19:16 -05:00
};