欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 让C++处理JSON类型配置文件更轻松-Hjson-cpp详解

让C++处理JSON类型配置文件更轻松-Hjson-cpp详解

2025/6/18 21:06:23 来源:https://blog.csdn.net/qq_15181569/article/details/148706338  浏览:    关键词:让C++处理JSON类型配置文件更轻松-Hjson-cpp详解

让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;
}

运行查看结果:
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词