cereal是一个非常方便和强大的序列化开源库,可以和Qt5结合使用。
https://blog.csdn.net/gx864102252/article/details/81273742
https://www.findbestopensource.com/product/wush978-rcereal
当然boost.serialization也是可以的
https://www.cnblogs.com/cmranger/p/4772149.html
用过C#序列化的都会感觉非常方便和实用
1。实现写操作
CerealDates.h
#ifndef CEREALDATES_H
#define CEREALDATES_H
#include <iostream>
#include <fstream>
#include <string>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/string.hpp> //一定要包含此文件,否则无法将std::string序列化为二进制形式,请看:https://github.com/USCiLab/cereal/issues/58
class CerealDates
{
public:
CerealDates();
public:
int x, y;
float z;
template<class Archive>
void serialize(Archive & ar)
{
ar(CEREAL_NVP(x), CEREAL_NVP(y), CEREAL_NVP(z));
}
void set(int in1, int in2, float in3);
void get(int &out1, int &out2, float &out3);
};
#endif // CEREALDATES_H
CerealDatesOp.h
#ifndef CEREALDATESOP_H
#define CEREALDATESOP_H
#include "cerealdates.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/string.hpp> //一定要包含此文件,
#include <QString>
class CerealDatesOp
{
public:
CerealDatesOp();
QString filePath;
CerealDates m_CerealDates;
void load();
void save();
};
#endif // CEREALDATESOP_H
CerealDatesOp.cpp
#include "cerealdatesop.h"
#include <QDebug>
CerealDatesOp::CerealDatesOp()
{
filePath = "D:/cereal.json";
int x = 0; int y =0;
float z = .0;
m_CerealDates.get(x, y, z);
qDebug() << "x: " << x << " y: " << y << " z: " << z;
m_CerealDates.set(5, 66, 3.1415);
m_CerealDates.get(x, y, z);
qDebug() << "x: " << x << " y: " << y << " z: " << z;
save();
}
void CerealDatesOp::load()
{
CerealDates list;
std::fstream in;
{
in.open(filePath.toStdString(), std::ios::in);
cereal::JSONInputArchive archive(in);
archive(list);
}
in.close();
m_CerealDates = list;
}
void CerealDatesOp::save()
{
qDebug() << "save begein: ";
std::ofstream out;
{
out.open(filePath.toStdString(), std::ios::trunc);
cereal::JSONOutputArchive archive(out);
archive(m_CerealDates);
}
out.close();
qDebug() << "save end";
}
测试代码:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CerealDatesOp op;
可以看到生成的文件
2。进行读数据操作
CerealDatesOp::CerealDatesOp()
{
filePath = "D:/cereal.json";
int x = 0; int y =0;
float z = .0;
// m_CerealDates.get(x, y, z);
// qDebug() << "x: " << x << " y: " << y << " z: " << z;
// m_CerealDates.set(5, 66, 3.1415);
// m_CerealDates.get(x, y, z);
// qDebug() << "x: " << x << " y: " << y << " z: " << z;
// save();
load();
m_CerealDates.get(x, y, z);
qDebug() << "x: " << x << " y: " << y << " z: " << z;
}
运行结果:
多谢,亲爱的美美。