讓C++處理JSON類型配置文件更輕松-Hjson-cpp詳解
- 一、Hjson-Cpp簡介
- Hjson-Cpp簡介
- 核心特性
- 安裝與集成
- 基本用法示例
- 常用API說明
- 與JSON互轉
- 錯誤處理
- 性能建議
- 高級特性
- 1. 類型安全訪問
- 2. 文件操作
- 3. 自定義解析規則
- 二、使用教程
- 下載
- 使用
一、Hjson-Cpp簡介
Hjson-Cpp簡介
Hjson-Cpp是C++實現的Hjson解析庫。Hjson(Human JSON)是JSON的擴展格式,支持注釋、多行字符串等更友好的語法,適用于配置文件等場景。Hjson-Cpp提供將Hjson轉換為JSON或直接解析為C++對象的功能。
- 支持注釋:單行(//)和多行(/* */)注釋
- 寬松語法:字符串可以不加引號,末尾逗號可省略
- 多行字符串:更自然的文本塊表示
- 更友好的錯誤提示:定位配置錯誤更直觀
核心特性
- 支持標準Hjson語法,包括注釋(
#
或//
)、無引號鍵名、多行字符串。 - 提供與JSON互轉的能力,兼容現有JSON工具鏈。
- 輕量級實現,僅依賴C++11標準庫。
安裝與集成
使用CMake集成Hjson-cpp:
find_package(hjsoncpp REQUIRED)
target_link_libraries(your_target PRIVATE hjsoncpp)
或手動下載源碼后,將include/hjson
目錄添加到項目頭文件路徑。
基本用法示例
解析Hjson字符串并讀取內容:
#include <hjson/hjson.h>
#include <iostream>
#include <fstream>int main() {// 從字符串解析std::string configStr = R"(// 這是一個Hjson配置示例{appName: My Application // 字符串可以不加引號version: 1.2.3features: ["fast-mode" // 引號也是允許的dark-theme // 這種寫法也可以auto-save // 最后一個元素可以不加逗號]/* 多行注釋 */timeout: 30s // 帶單位的數值})";Hjson::Value config;try {config = Hjson::Unmarshal(configStr);// 訪問數據std::cout << "App: " << config["appName"].to_string() << "\n";std::cout << "Version: " << config["version"].to_double() << "\n";// 遍歷數組std::cout << "Features:\n";for (auto& feature : config["features"]) {std::cout << " - " << feature.to_string() << "\n";}} catch (Hjson::syntax_error& e) {std::cerr << "配置語法錯誤: " << e.what() << "\n";return1;}return0;
}
常用API說明
Hjson::Marshal(value)
:將C++對象序列化為Hjson字符串。Hjson::Unmarshal(text)
:解析Hjson文本為Hjson::Value
對象。value.to_string()
/to_int()
:類型轉換方法。value[key]
:訪問對象成員或數組元素。
與JSON互轉
將JSON轉為Hjson(保留注釋等擴展特性):
Hjson::Value jsonData = Hjson::Unmarshal(jsonText);
std::string hjsonText = Hjson::Marshal(jsonData);
錯誤處理
解析失敗時拋出Hjson::syntax_error
異常:
try {Hjson::Unmarshal("invalid hjson");
} catch (const Hjson::syntax_error& e) {std::cerr << "Error: " << e.what() << "\n";
}
性能建議
- 對于大型文件,優先使用
UnmarshalFromFile
直接讀取文件。 - 頻繁操作時可復用
Hjson::Value
對象減少內存分配。
高級特性
1. 類型安全訪問
// 安全獲取配置值(帶默認值)
std::string appName = config.get("appName", "Default App");
int timeout = config.get("timeout", 10); // 自動類型轉換// 檢查類型
if (config["features"].type() == Hjson::Type::Vector) {std::cout << "features是數組類型\n";
}// 類型轉換方法
double version = config["version"].to_double();
std::string versionStr = config["version"].to_string(); // 自動轉換
2. 文件操作
// 從文件加載配置
try {Hjson::Value fileConfig = Hjson::UnmarshalFromFile("config.hjson");// 修改配置fileConfig["lastRun"] = Hjson::Value(time(nullptr));// 寫回文件(保留注釋和格式)Hjson::MarshalToFile(fileConfig, "config.hjson");
} catch (Hjson::file_error& e) {std::cerr << "文件操作失敗: " << e.what() << "\n";
}
3. 自定義解析規則
// 解析帶單位的數值
Hjson::DecoderOptions options;
options.unitResolver = [](const std::string& unit, double value) {if (unit == "s") return value * 1000; // 秒轉毫秒if (unit == "min") return value * 60 * 1000;return value;
};Hjson::Value customConfig = Hjson::Unmarshal("timeout: 30s", options);
std::cout << "Timeout in ms: " << customConfig["timeout"].to_int64() << "\n";
二、使用教程
下載
點擊https://github.com/hjson/hjson-cpp跳轉到github:
點擊Download
下載源碼。
或在文章頂部下載。
使用
VS新建工程:
拷貝Hjson源碼進入工程目錄:
編寫測試代碼:
#include <iostream>
#include "hjson.h"using namespace std;static const char* _szDefaultConfig = R"(
{imageSource: NO DEFAULTshowImages: truewriteImages: trueprintFrameIndex: falseprintFrameRate: true
}
)";Hjson::Value GetConfig(const char* szConfigPath) {Hjson::Value defaultConfig = Hjson::Unmarshal(_szDefaultConfig);Hjson::Value inputConfig;try {inputConfig = Hjson::UnmarshalFromFile(szConfigPath);}catch (const std::exception& e) {std::fprintf(stderr, "Error in config: %s\n\n", e.what());std::fprintf(stdout, "Default config:\n");std::fprintf(stdout, _szDefaultConfig);return Hjson::Value();}return Hjson::Merge(defaultConfig, inputConfig);
}int main()
{string path = "C:\\Users\\徐鵬\\Desktop\\hjson\\test.json";Hjson::Value val = GetConfig(path.c_str());printf("%s\r\n",val["imageSource"].to_string().c_str());Hjson::Value a = val.at("showImages");printf("%d\r\n", a.to_int64());return 0;
}
運行查看結果: