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;

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

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

相关推荐
奔跑的蜗牛AZ10 天前
TiDB 字符串行转列与 JSON 数据查询优化知识笔记
笔记·json·tidb
jarctique12 天前
java 找出两个json文件的不同之处
java·json
wtsolutions12 天前
Excel to JSON online converter, flat and nested JSON converter
json·excel·excel-to-json·wtsolutions
漫谈网络13 天前
JSON 数据格式详解
网络·python·json·数据格式
lwb_011814 天前
Spring MVC参数绑定终极手册:单&多参对象集合JSON文件上传精讲
spring·json·mvc
电商数据girl14 天前
【经验分享】浅谈京东商品SKU接口的技术实现原理
java·开发语言·前端·数据库·经验分享·eclipse·json
亚林瓜子14 天前
AWS S3拒绝非https的请求访问
https·云计算·json·ssl·aws·s3
于本淡15 天前
一篇文章快速学会HTML
开发语言·前端·数据结构·qt·html·json·html5
HaiQinyanAN16 天前
【学习笔记】nlohmannjson&&cjson
c++·笔记·学习·json
Code季风16 天前
学习 Protobuf:序列化、反序列化及与 JSON 的对比
学习·rpc·golang·json