JSON头文件调用

除了传统的读写操作,现在流行的json文件读取保存,还是非常方便的.

头文件放在源代码中,在调用处添加引用路径

#include ".../ConsoleApplication1/include/json.hpp"

using json = nlohmann::json;

数据结构例子:

// 声明Person类

class Person {

public:

std::string name;

int age;

复制代码
// 构造函数
Person(std::string n, int a) : name(n), age(a) {}

// 序列化到JSON
json to_json() const {
    return { {"name", name}, {"age", age} };
}

// 反序列化从JSON

static Person from_json(const json& j) {

std::string n = j.at("name").getstd::string();

int a = j.at("age").get();

return Person(n, a);

}

};

调用实例:

Person person("LiLma", 15);

serialize_to_file(person, "person.json");

复制代码
Person restored_person = deserialize_from_file("person.json");
std::cout << "Restored Person: " << restored_person.name << ", " << restored_person.age << std::endl;

以后读取文件可以更方便,更有效,不用在那么麻烦啦.

可以转换成你需要的任何类型,数据读取写入太方便了.

相关推荐
Venuslite2 天前
从 Unexpected token < 到 Extra data:一次讲清 JSON 解析错误的排查思路
json
疯狂SQL8 天前
手写高性能在线 JSON 工具|Web Worker 工程化打包 + 语法自动修复 + 多语言代码生成实战
typescript·json·next.js·web worker·前端性能优化·esbuild·源码实战
terry60013 天前
5G视频短信服务商选型全攻略:通道资源、架构能力与成本评估2026最新标准
大数据·人工智能·5g·json·asp.net·信息与通信·数据库架构
前网易架构师-高司机13 天前
带标注的辣椒病叶数据集,识别率95.9%,可识别三种病害和健康叶子,9916张图,支持yolo,coco json,voc xml,文末有模型训练代码
yolo·json·数据集·病害·叶病·病叶·辣椒
PixelBai13 天前
JSON扁平化使用教程:从入门到精通
json
渔舟唱晚,雁阵惊寒14 天前
CSDN博客内容丢失如何恢复?
json
衣乌安、14 天前
JSON-RPC协议
网络协议·rpc·json
PixelBai14 天前
JSON过滤使用教程:从入门到精通
javascript·chrome·json
PixelBai14 天前
JSON过滤实际应用场景案例
json