C++ Hjson-cpp處理JSON類(lèi)型配置文件詳解
Hjson-Cpp簡(jiǎn)介
Hjson-Cpp是C++實(shí)現(xiàn)的Hjson解析庫(kù)。Hjson(Human JSON)是JSON的擴(kuò)展格式,支持注釋、多行字符串等更友好的語(yǔ)法,適用于配置文件等場(chǎng)景。Hjson-Cpp提供將Hjson轉(zhuǎn)換為JSON或直接解析為C++對(duì)象的功能。
- 支持注釋?zhuān)簡(jiǎn)涡?//)和多行(/* */)注釋
- 寬松語(yǔ)法:字符串可以不加引號(hào),末尾逗號(hào)可省略
- 多行字符串:更自然的文本塊表示
- 更友好的錯(cuò)誤提示:定位配置錯(cuò)誤更直觀
核心特性
支持標(biāo)準(zhǔn)Hjson語(yǔ)法,包括注釋?zhuān)?或//)、無(wú)引號(hào)鍵名、多行字符串。
提供與JSON互轉(zhuǎn)的能力,兼容現(xiàn)有JSON工具鏈。
輕量級(jí)實(shí)現(xiàn),僅依賴(lài)C++11標(biāo)準(zhǔn)庫(kù)。
安裝與集成
使用CMake集成Hjson-cpp:
find_package(hjsoncpp REQUIRED) target_link_libraries(your_target PRIVATE hjsoncpp)
或手動(dòng)下載源碼后,將include/hjson目錄添加到項(xiàng)目頭文件路徑。
基本用法示例
解析Hjson字符串并讀取內(nèi)容:
#include <hjson/hjson.h>
#include <iostream>
#include <fstream>
int main() {
// 從字符串解析
std::string configStr = R"(
// 這是一個(gè)Hjson配置示例
{
appName: My Application // 字符串可以不加引號(hào)
version: 1.2.3
features: [
"fast-mode" // 引號(hào)也是允許的
dark-theme // 這種寫(xiě)法也可以
auto-save // 最后一個(gè)元素可以不加逗號(hào)
]
/* 多行
注釋 */
timeout: 30s // 帶單位的數(shù)值
}
)";
Hjson::Value config;
try {
config = Hjson::Unmarshal(configStr);
// 訪問(wèn)數(shù)據(jù)
std::cout << "App: " << config["appName"].to_string() << "\n";
std::cout << "Version: " << config["version"].to_double() << "\n";
// 遍歷數(shù)組
std::cout << "Features:\n";
for (auto& feature : config["features"]) {
std::cout << " - " << feature.to_string() << "\n";
}
} catch (Hjson::syntax_error& e) {
std::cerr << "配置語(yǔ)法錯(cuò)誤: " << e.what() << "\n";
return1;
}
return0;
}
常用API說(shuō)明
Hjson::Marshal(value):將C++對(duì)象序列化為Hjson字符串。
Hjson::Unmarshal(text):解析Hjson文本為Hjson::Value對(duì)象。
value.to_string()/to_int():類(lèi)型轉(zhuǎn)換方法。
value[key]:訪問(wèn)對(duì)象成員或數(shù)組元素。
與JSON互轉(zhuǎn)
將JSON轉(zhuǎn)為Hjson(保留注釋等擴(kuò)展特性):
Hjson::Value jsonData = Hjson::Unmarshal(jsonText); std::string hjsonText = Hjson::Marshal(jsonData);
錯(cuò)誤處理
解析失敗時(shí)拋出Hjson::syntax_error異常:
try {
Hjson::Unmarshal("invalid hjson");
} catch (const Hjson::syntax_error& e) {
std::cerr << "Error: " << e.what() << "\n";
}
性能建議
對(duì)于大型文件,優(yōu)先使用UnmarshalFromFile直接讀取文件。
頻繁操作時(shí)可復(fù)用Hjson::Value對(duì)象減少內(nèi)存分配。
高級(jí)特性
1. 類(lèi)型安全訪問(wèn)
// 安全獲取配置值(帶默認(rèn)值)
std::string appName = config.get("appName", "Default App");
int timeout = config.get("timeout", 10); // 自動(dòng)類(lèi)型轉(zhuǎn)換
// 檢查類(lèi)型
if (config["features"].type() == Hjson::Type::Vector) {
std::cout << "features是數(shù)組類(lèi)型\n";
}
// 類(lèi)型轉(zhuǎn)換方法
double version = config["version"].to_double();
std::string versionStr = config["version"].to_string(); // 自動(dòng)轉(zhuǎn)換
2. 文件操作
// 從文件加載配置
try {
Hjson::Value fileConfig = Hjson::UnmarshalFromFile("config.hjson");
// 修改配置
fileConfig["lastRun"] = Hjson::Value(time(nullptr));
// 寫(xiě)回文件(保留注釋和格式)
Hjson::MarshalToFile(fileConfig, "config.hjson");
} catch (Hjson::file_error& e) {
std::cerr << "文件操作失敗: " << e.what() << "\n";
}
3. 自定義解析規(guī)則
// 解析帶單位的數(shù)值
Hjson::DecoderOptions options;
options.unitResolver = [](const std::string& unit, double value) {
if (unit == "s") return value * 1000; // 秒轉(zhuǎn)毫秒
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";
使用教程
下載
點(diǎn)擊https://github.com/hjson/hjson-cpp跳轉(zhuǎn)到github:

點(diǎn)擊Download下載源碼。

使用
VS新建工程:

拷貝Hjson源碼進(jìn)入工程目錄:

編寫(xiě)測(cè)試代碼:
#include <iostream>
#include "hjson.h"
using namespace std;
static const char* _szDefaultConfig = R"(
{
imageSource: NO DEFAULT
showImages: true
writeImages: true
printFrameIndex: false
printFrameRate: 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;
}
運(yùn)行查看結(jié)果:

到此這篇關(guān)于C++ Hjson-cpp處理JSON類(lèi)型配置文件詳解的文章就介紹到這了,更多相關(guān)C++處理JSON內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
簡(jiǎn)單總結(jié)C語(yǔ)言中各種類(lèi)型的指針的概念
這篇文章主要簡(jiǎn)單總結(jié)了C語(yǔ)言中各種類(lèi)型的指針的概念,指針可以說(shuō)是C語(yǔ)言本身所具有的最大特性,平時(shí)根據(jù)不同使用場(chǎng)合習(xí)慣地將其簡(jiǎn)單分類(lèi),需要的朋友可以參考下2016-03-03
c語(yǔ)言中單引號(hào)和雙引號(hào)的區(qū)別(順利解決從字符串中提取IP地址的困惑)
c語(yǔ)言中的單引號(hào)和雙引號(hào)可是有很大區(qū)別的,使用之前一定要了解他們之間到底有什么不同,下面小編就給大家詳細(xì)的介紹一下吧,對(duì)此還不是很了解的朋友可以過(guò)來(lái)參考下2013-07-07
詳細(xì)聊聊c語(yǔ)言中的緩沖區(qū)問(wèn)題
緩沖區(qū)又稱(chēng)為緩存,它是內(nèi)存空間的一部分,也就是說(shuō)在內(nèi)存空間中預(yù)留了一定的存儲(chǔ)空間,這些存儲(chǔ)空間用來(lái)緩沖輸入或輸出的數(shù)據(jù),這部分預(yù)留的空間就叫做緩沖區(qū),這篇文章主要給大家介紹了關(guān)于c語(yǔ)言中緩沖區(qū)問(wèn)題的相關(guān)資料,需要的朋友可以參考下2021-11-11
vscode配置遠(yuǎn)程開(kāi)發(fā)環(huán)境并遠(yuǎn)程調(diào)試運(yùn)行C++代碼的教程
這篇文章主要介紹了vscode配置遠(yuǎn)程開(kāi)發(fā)環(huán)境并遠(yuǎn)程調(diào)試運(yùn)行C++代碼的教程,本文通過(guò)截圖實(shí)例相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04

