C++使用nlohmann json

本文深入解析了C++中最受欢迎的JSON库nlohmann的使用方法,包括编译安装步骤、基本类型和复杂类型的序列化与反序列化过程,以及自定义类型序列化的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最好用的c++ json库是 nlohmann
github 地址:https://github.com/nlohmann/json.git

提示

把变量写成json容易,可是把json变成变量就要复杂一点,不过对于nlohmann一点都不复杂

json是什么

不多说了

怎么使用这个库

编译安装

mkdir build
cd build
cmake ..
make
sudo make install

头文件

#include "nlohmann/json.hpp"    //实际位置在 /usr/include中,so和a文件也在默认的地方

写json

对于基本类型,直接赋值,简单粗暴
对于复杂类型,要自定义函数,使用基本类型来实现
#include "nlohmann/json.hpp"
#include <iostream>
#include <fstream>
#include <eigen3/Eigen/Eigen>

using json = nlohmann::json;

using namespace std;
using namespace Eigen;

int main()
{
	nlohmann::json json;
    Eigen::Vector3d o(3,4,5);
    Eigen::Quaterniond origin_(2, 0, 1, -3);
    json["id"] = id;
    json["map_type"] = type_;
    nlohmann::json json_origin_position;
    json_origin_position["x"] = o.x();
    json_origin_position["y"] = o.y();
    json_origin_position["z"] = o.z();
    nlohmann::json json_origin_rotation;
    json_origin_rotation["w"] = origin_.w();
    json_origin_rotation["x"] = origin_.x();
    json_origin_rotation["y"] = origin_.y();
    json_origin_rotation["z"] = origin_.z();
    nlohmann::json json_origin;
    json_origin["position"] = json_origin_position;
    json_origin["rotation"] = json_origin_rotation;
    json["origin"] = json_origin;
    cout << json.dump(2) << std::endl;
    std::ofstream os("test.json");
    os << json.dump(4) << endl;
    return 0;
}

读json

  1. 使用 json["somename"].get<T>(),如 basictype x = json["somename"].get<basictype>();
  2. 使用 json.at("somename").get_to(variable)
  3. 对于自定义的类型,需要序列化你的class或者struct,即加上序列化方法from_json(const json& json, T& var)
struct hl{
    int id;
};
}
hl  m = json["name"].get<hl>(); //错误

需要为struct hl加上序列化方法from_json(const json& json, hl* var)
修改上面的struct hl

struct hl{
    int id;
};

void from_json(const json& j, hl& h){
    j.at("id").get_to(h.id);
}
hl  m = json["name"].get<hl>(); //正确
  1. 对于class定义的类型,可以将上面的 from_json方法改成 friend型,这样就可以访问class的私有变量啦
### 如何使用 C++nlohmann/json 库创建并生成 JSON 文件 以下是关于如何利用 `nlohmann::json` 库在 C++ 中创建和生成 JSON 文件的具体方法: #### 添加库到项目 为了使用 `nlohmann::json`,需要先将其集成到开发环境中。可以通过从 GitHub 下载单个头文件 `json.hpp` 并添加到项目的目录中完成此操作[^2]。 ```cpp #include <iostream> #include <fstream> // 用于文件写入 #include <nlohmann/json.hpp> using json = nlohmann::json; ``` #### 创建 JSON 对象 通过定义变量类型为 `nlohmann::json` 来初始化一个 JSON 对象。可以手动构建简单的键值对或者嵌套结构来表示复杂的 JSON 数据[^3]。 ```cpp int main() { // 构建基础的JSON对象 json j_object = { {"name", "John Doe"}, {"age", 30}, {"is_student", false} }; std::cout << j_object.dump(4) << std::endl; // 输出带缩进格式化后的字符串形式 } ``` 上述代码展示了如何创建一个基本的对象类型的 JSON 实体,并打印出来以便验证其内容是否符合预期。 #### 追加方式存储 JSON 到文件 如果希望以追加的形式保存多个独立记录进入同一个 JSON 文件,则需考虑数组型别的容器作为顶层节点,每次新增数据项时都向其中增加新成员再整体写出更新版本的内容至磁盘上指定位置[^1]。 ```cpp void appendToJsonFile(const std::string& filename, const json& new_entry){ try{ std::ifstream ifs(filename); // 如果文件存在则读取现有内容;否则视为新建空列表 json data = (ifs.good()) ? json::parse(ifs) : json::array(); // 向数组末尾加入新的条目 data.push_back(new_entry); // 关闭输入流准备覆盖原文件或首次写入 ifs.close(); // 打开输出流设置成截断模式(truncate),即清空旧有内容重新填写最新状态的数据集 std::ofstream ofs(filename); if(!ofs.is_open()){ throw std::runtime_error("Failed to open file for writing."); } // 将最终结果序列化为美化过的文本串后存档 ofs << data.dump(4); ofs.flush(); // 确保缓冲区中的信息立即被刷入硬盘 ofs.close(); } catch(std::exception &e){ std::cerr << e.what() << '\n'; } } // 调用函数实例演示 appendToJsonFile("example.json", j_object); ``` 以上片段解释了一个实用场景下的实现细节——动态维护一份持久化的日志类文档资源集合。每当调用了这个辅助功能之后都会自动把传进去的那个单独实体附加到目标路径所指向的目标文件里去。 #### 完整示例程序 下面给出的是综合运用前面介绍知识点的一个完整例子,它不仅包含了必要的头部声明部分还实现了实际业务逻辑处理流程以及错误捕捉机制等方面考量因素在内的全貌视图供参考学习之用: ```cpp #include <iostream> #include <fstream> #include <nlohmann/json.hpp> using namespace std; using json = nlohmann::json; void saveJsonToFile(const string& fileName, const json& jsonData){ ofstream outFile(fileName); if(outFile.is_open()){ outFile << jsonData.dump(4); outFile.close(); }else{ cerr << "Unable to open file: " << fileName << endl; } } int main(){ // Create a sample JSON object. json person = { {"first_name","Jane"}, {"last_name","Doe"}, {"address",{ {"street","Baker Street"}, {"city","London"} }}, {"phone_numbers",{"home","+44 7900 123456"}} }; cout << "Generated JSON:\n" << person.dump(4) << "\n"; // Save the generated JSON into 'output.json'. saveJsonToFile("output.json",person); return 0; } ``` 运行这段脚本将会生成名为 `output.json` 的本地文件,里面填充着我们预先设定好的测试样本人物资料卡片样式的信息表达式描述。 ---
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值