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;

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

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

相关推荐
Martin-Luo2 天前
Vue3 通过json配置生成查询表单
javascript·vue.js·json
星尘库2 天前
后端json数据反序列化枚举类型不匹配的错误
json
BXCQ_xuan2 天前
软件工程实践四:MyBatis-Plus 教程(连接、分页、查询)
spring boot·mysql·json·mybatis
王维志2 天前
LiteDB详解
数据库·后端·mongodb·sqlite·c#·json·database
ID_180079054732 天前
Python采集京东店铺所有商品数据,json数据返回
json
ljh5746491192 天前
mysql 必须在逗号分隔字符串和JSON字段之间二选一,怎么选
数据库·mysql·json
小孔龙2 天前
02.Kotlin Serialization 属性序列化控制
kotlin·json
Cachel wood3 天前
信息检索、推荐系统模型排序质量指标:AP@K和MAP@K
windows·搜索引擎·json·推荐系统·搜索
tebukaopu1483 天前
json文件转excel
json·excel
小孔龙4 天前
01.Kotlin Serialization - 基础用法
kotlin·json