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;

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

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

相关推荐
热爱学习的小翁同学8 小时前
SharePoint 列格式化 JSON 配置
json·sharepoint
qq_3380329211 小时前
Vue/JS项目的package.json文件 和java项目里面的pom文件
java·javascript·vue.js·json
wtsolutions14 小时前
Sheet-to-Doc Supports JSON and JSONL: New Way to Batch Generate Word Documents
json·word·batch
@zulnger15 小时前
爬虫库之 requests_html,json
爬虫·html·json
2501_915909061 天前
如何保护 iOS IPA 文件中资源与文件的安全,图片、JSON重命名
android·ios·小程序·uni-app·json·iphone·webview
组合缺一1 天前
Json Dom 怎么玩转?
java·json·dom·snack4
wtsolutions1 天前
MCP Server Integration - JSON to Excel for AI and Automation
json·excel
\xin1 天前
Fastjson 1.2.45仅JSON接口反序列化漏洞
安全·web安全·json
司机20481 天前
将virtuoso原理图信息导出到json文件
json·github
Sylvia33.2 天前
网球/羽毛球数据API:专业赛事数据服务的技术实现
java·前端·websocket·json