Files
eUi/include/generalJsonParsing.hpp
2025-08-15 16:36:54 +08:00

126 lines
3.4 KiB
C++

#include <nlohmannJson.hpp>
#include <fstream>
// 读取json文件,不按顺序
static nlohmann::json readJsonFromPath(std::string path)
{
nlohmann::json jsonObj;
std::ifstream inputFile(path);
if (!inputFile.is_open()) {
std::cerr << "Could not open the file - " << path << std::endl;
return jsonObj;
}
try {
inputFile >> jsonObj;
}
catch (nlohmann::json::parse_error& e) {
std::cerr << "JSON parse error: " << e.what() << std::endl;
return jsonObj;
}
// 关闭文件
inputFile.close();
return jsonObj;
}
// 保存json文件,不按顺序
static bool saveJsonFromPath(std::string path, nlohmann::json& json)
{
std::ofstream saveFile(path);
if (!saveFile.is_open()) {
std::cerr << "Could not open the file - " << path << std::endl;
return false;
}
try {
saveFile << json.dump(4);
}
catch (nlohmann::json::parse_error& e) {
std::cerr << "JSON parse error: " << e.what() << std::endl;
return false;
}
// 关闭文件
saveFile.close();
return true;
}
// 读取有序 JSON 文件
static nlohmann::ordered_json readOrderedJsonFromPath(const std::string& path)
{
nlohmann::ordered_json jsonObj;
std::ifstream inputFile(path);
if (!inputFile.is_open()) {
std::cerr << "Could not open the file - " << path << std::endl;
return jsonObj;
}
try {
inputFile >> jsonObj;
}
catch (const nlohmann::json::parse_error& e) {
std::cerr << "JSON parse error: " << e.what() << std::endl;
return nlohmann::ordered_json();
}
return jsonObj;
}
// 保存有序 JSON 文件
static bool saveOrderedJsonFromPath(const std::string& path, const nlohmann::ordered_json& json)
{
std::ofstream saveFile(path);
if (!saveFile.is_open()) {
std::cerr << "Could not open the file - " << path << std::endl;
return false;
}
try {
saveFile << json.dump(4); // 缩进4空格
}
catch (const nlohmann::json::type_error& e) {
std::cerr << "JSON write error: " << e.what() << std::endl;
return false;
}
return true;
}
static void printNlohmannJson(nlohmann::json input, int depth = 0)
{
std::string indent_str(depth, ' ');
// 处理 JSON 对象
if (input.is_object()) {
std::cout << indent_str << "{\n";
for (auto it = input.begin(); it != input.end(); ++it) {
std::cout << indent_str << " \"" << it.key() << "\": ";
printNlohmannJson(it.value(), depth + 2);
}
std::cout << indent_str << "}\n";
}
// 处理 JSON 数组
else if (input.is_array()) {
std::cout << indent_str << "[\n";
for (const auto& element : input) {
printNlohmannJson(element, depth + 2);
}
std::cout << indent_str << "]\n";
}
// 处理 JSON 字符串
else if (input.is_string()) {
std::cout << indent_str << "\"" << input.get<std::string>() << "\"\n";
}
// 处理 JSON 数字
else if (input.is_number()) {
std::cout << indent_str << input << "\n";
}
// 处理 JSON 布尔值
else if (input.is_boolean()) {
std::cout << indent_str << (input.get<bool>() ? "true" : "false") << "\n";
}
// 处理 JSON null
else if (input.is_null()) {
std::cout << indent_str << "null\n";
}
}
#pragma once