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;

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

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

相关推荐
guslegend4 小时前
AI生图第3节:gpt-image-2的提示词反解析与Json结构化生图
人工智能·gpt·json
wtsolutions8 小时前
Excel-to-JSON Local App - Secure Offline Excel to JSON Conversion
json·excel
Hello_Embed11 小时前
嵌入式上位机开发入门(二十九):JsonRPC TCP Server
网络·单片机·网络协议·tcp/ip·json·嵌入式
七夜zippoe1 天前
DolphinDB数据导入导出:CSV、JSON、Parquet
物联网·json·csv·parquet·dolphindb
qq_452396231 天前
第七篇:《数据驱动测试:利用Excel/JSON/CSV管理测试数据》
json·excel
sagima_sdu2 天前
Codex 使用指南(技术向):App、CLI 与工作流接入
linux·运维·语言模型·json
小糖学代码3 天前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
赵庆明老师4 天前
vben开发入门6:tsconfig.json
json·vue3·vben
jnrjian4 天前
DR$ JSON_INDEX $DG表的处理 Json search index data guide
oracle·json