How to serialize data using Qt
Qt provides two classes for serialization, DataStream class to serialization of binary data and QTextStream to “parsing” input stream(reading and writing text). QDataStream class can be used to write portables files (i.e., a data stream written under Windows can be read by other running GNU/Linux or Solaris).
Thus, there are situations that serialization of binary data are very useful to us, for example, create a dictionary like a configuration file. In our example, we write, update and read a QHash(our dictionary).See the list of data types which can be serialized here
#include <QtCore>
#include <QApplication>
#include <QHash>
#include <QFile>
#include <QDataStream>
#define PATH "./file.dat"
int main()
{
//create a dictionary
QHash<QString,QString> dict;
dict["project.owner"] = “owner”;
dict["project.version"] = “0.10.0″;
QFile file(PATH);
file.open(QIODevice::WriteOnly);
QDataStream out(&file); // write the data
out << dict;
file.close();
//setting new a value
dict["project.owner"] = “new”;
//update the dictionary
file.open(QIODevice::ReadOnly);
QDataStream in(&file); // read the data serialized from the file
in >> dict;
qDebug() << “value: ” << dict.value(”project.owner”);
return 0;
}
Leave a comment