使用jsoncpp库可高效读写JSON文件。首先通过包管理器或源码安装jsoncpp,再在C++项目中包含头文件并链接库。读取时用Json::CharReaderBuilder解析文件内容到Json::Value对象,写入时用Json::StreamWriterBuilder将Json::Value写入文件。支持字符串、数值、布尔、数组、对象等类型操作,需检查文件打开与解析是否成功,确保程序健壮性。

在C++中读写JSON文件,使用jsoncpp库是一个简单高效的选择。jsoncpp提供清晰的API来解析、生成和操作JSON数据,适合嵌入到项目中处理配置文件、网络通信数据等场景。
在使用前需要将jsoncpp集成到你的C++项目中:
使用Json::Value和Json::Reader(新版推荐使用Json::CharReader)解析JSON文件内容:
#include <json/json.h>
#include <fstream>
#include <iostream>
bool readJsonFile(const std::string& filename, Json::Value& root) {
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "无法打开文件: " << filename << std::endl;
return false;
}
Json::CharReaderBuilder builder;
std::string errs;
if (!parseFromStream(builder, ifs, &root, &errs)) {
std::cerr << "解析失败: " << errs << std::endl;
return false;
}
return true;
}
// 使用示例
int main() {
Json::Value config;
if (readJsonFile("config.json", config)) {
std::cout << "姓名: " << config["name"].asString() << std::endl;
std::cout << "年龄: " << config["age"].asInt() << std::endl;
// 遍历数组
const Json::Value items = config["items"];
for (const auto& item : items) {
std::cout << "物品: " << item.asString() << std::endl;
}
}
return 0;
}
使用Json::Value构建数据结构,并通过Json::StreamWriter写入文件:
立即学习“C++免费学习笔记(深入)”;
bool writeJsonFile(const std::string& filename, const Json::Value& root) {
std::ofstream ofs(filename);
if (!ofs.is_open()) {
std::cerr << "无法创建文件: " << filename << std::endl;
return false;
}
Json::StreamWriterBuilder builder;
builder["indentation"] = " "; // 设置缩进为两个空格
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
writer->write(root, &ofs);
return true;
}
// 写入示例
int main() {
Json::Value root;
root["name"] = "张三";
root["age"] = 25;
root["city"] = "北京";
Json::Value items;
items.append("苹果");
items.append("香蕉");
root["items"] = items;
writeJsonFile("output.json", root);
std::cout << "JSON文件写入完成" << std::endl;
return 0;
}
Json::Value支持多种数据类型的读取和设置:
基本上就这些。只要正确引入jsoncpp,读写JSON文件并不复杂,关键是处理好文件流和解析错误。开发时建议开启编译选项-Wall,并检查返回值,确保程序健壮性。
以上就是c++++如何读写JSON文件_c++集成jsoncpp库进行数据解析的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号