c++如何读写JSON文件_c++集成jsoncpp库进行数据解析

1次阅读

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

c++如何读写JSON文件_c++集成jsoncpp库进行数据解析

在C++中读写JSON文件,使用jsoncpp库是一个简单高效的选择。jsoncpp提供清晰的API来解析、生成和操作JSON数据,适合嵌入到项目中处理配置文件、网络通信数据等场景。

安装与集成jsoncpp库

在使用前需要将jsoncpp集成到你的C++项目中:

  • ubuntu/debian系统可通过包管理器安装:
    sudo apt install libjsoncpp-dev
  • 手动编译:从gitHub下载源码(https://github.com/open-source-parsers/jsoncpp),使用cmake构建并安装
  • CMake项目中可使用find_package(JsonCpp REQUIRED)自动链接
  • 或者直接将jsoncpp的头文件和静态库加入项目目录,手动指定include路径和链接库

读取JSON文件

使用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文件

使用Json::Value构建数据结构,并通过Json::StreamWriter写入文件:

c++如何读写JSON文件_c++集成jsoncpp库进行数据解析

Magick

无代码AI工具,可以构建世界级的AI应用程序。

c++如何读写JSON文件_c++集成jsoncpp库进行数据解析 225

查看详情 c++如何读写JSON文件_c++集成jsoncpp库进行数据解析

立即学习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支持多种数据类型的读取和设置:

  • asString():转为字符串
  • asInt(), asUInt(), asDouble():转为数值类型
  • asBool():转为布尔值
  • isObject() 判断是否为对象,可用迭代器遍历键值对
  • isArray() 判断是否为数组,可通过下标访问
  • 使用 isMember(“key”) 判断是否存在某个字段,避免访问空值

基本上就这些。只要正确引入jsoncpp,读写JSON文件并不复杂,关键是处理好文件流和解析错误。开发时建议开启编译选项-Wall,并检查返回值,确保程序健壮性。

text=ZqhQzanResources