CheatMenuSA/CheatMenu/Json.h

113 lines
2.0 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
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, '.'))
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, '.'))
json = &((*json)[line]);
// json library bugs with bool, using int instead
if (typeid(T) == typeid(bool))
*json = (val ? 1 : 0);
else
*json = val;
}
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
/*
2021-02-24 16:54:45 -05:00
Loads the section names into a category vector.
Used to create drop down category menus
*/
void LoadData(std::vector<std::string>& vec, std::string& selected);
/*
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
};