Qt Serialization

The purpose of serialization is to save the state of an object to be able to recreate it when needed. It allows you to perform actions like:

  • Sending the object to a remote application by using a web service
  • Passing the object as a JSON or XML string
  • Saving and restoring user information or sharing it across applications

The Qt API provides support for serialization for several use cases:

  • JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data. CBOR Support in Qt is a compact form of binary data encoding that is a superset of JSON.
  • QDataStream provides serialization of binary data to a QIODevice
  • Qt XML C++ 類 provide C++ implementations of the XML 流 and DOM standards for XML
  • CBOR is Qt's implementation for the CBOR serialization format.
  • QSettings provides a way of serializing and storing platform independent application settings.

Advantages of JSON and CBOR

When you use JSON information is stored in a QJsonObject QJsonDocument takes care to stream values into a QByteArray .

For example

QJsonObject jobject;
jobject["SensorID"] = m_id;
jobject["AmbientTemperature"] = m_ambientTemperature;
jobject["ObjectTemperature"] = m_objectTemperature;
jobject["AccelerometerX"] = m_accelerometerX;
jobject["AccelerometerY"] = m_accelerometerY;
jobject["AccelerometerZ"] = m_accelerometerZ;
jobject["Altitude"] = m_altitude;
jobject["Light"] = m_light;
jobject["Humidity"] = m_humidity;
QJsonDocument doc( jobject );
return doc.toJson();
					

JSON has several advantages:

  • Textual JSON is declarative, which makes it readable to humans
  • The information is structured
  • Exchanging generic information is easy
  • JSON allows extending messages with additional values
  • Many solutions exist to receive and parse JSON in cloud-based solutions

CBOR is the Concise Binary Object Representation, a very compact form of binary data encoding that is a superset of JSON. It was created by the IETF Constrained RESTful Environments (CoRE) WG, which has been used in many new RFCs. CBOR shares many of the advantages of JSON, but sacrifices human readability for compactness.

Advantages of QDataStream Classes

QDataStream is a viable option when the whole flow of data is determined and not about to change. In addition, both the reader and the writer of the data must be written in Qt.

Adding support for this to a class requires two additional operators. For example, for a class named SensorInformation:

QDataStream &operator<<(QDataStream &, const SensorInformation &);
QDataStream &operator>>(QDataStream &, SensorInformation &);
					

The implementation for the serialization is shown below:

QDataStream &operator<<(QDataStream &out, const SensorInformation &item)
{
    QDataStream::FloatingPointPrecision prev = out.floatingPointPrecision();
    out.setFloatingPointPrecision(QDataStream::DoublePrecision);
    out << item.m_id
        << item.m_ambientTemperature
        << item.m_objectTemperature
        << item.m_accelerometerX
        << item.m_accelerometerY
        << item.m_accelerometerZ
        << item.m_altitude
        << item.m_light
        << item.m_humidity;
    out.setFloatingPointPrecision(prev);
    return out;
}
					

Deserialization works similarly, but using the >> operator. For example, out >> item.m_id , and so on.

Usually, using QDataStream is faster than using textual JSON.

Advantages of Qt XML C++ Classes

Qt provides both DOM classes and stream-based classes to read and write XML content.

Qt 提供 QDomDocument class that represents the XML document and two classes for reading and writing the XML through a simple streaming API: QXmlStreamReader and QXmlStreamWriter .

The DOM XML Classes

QDomDocument class represents the entire XML document. It is the root of the document tree and provides primary access to the document's data.

The Stream-Based XML Classes

A stream reader reports an XML document as a stream of tokens. This differs from SAX as SAX applications provide handlers to receive XML events from the parser, whereas the QXmlStreamReader drives the loop, pulling tokens from the reader when they are needed. This pulling approach makes it possible to build recursive descent parsers, allowing XML parsing code to be split into different methods or classes.

QXmlStreamReader a parser for well-formed XML 1.0, excluding external parsed entities. Hence, data provided to the stream reader adheres to the W3C's criteria for well-formed XML, or an error will be raised. Functions such as atEnd() , error() ,和 hasError() can be used to test for such errors and obtain a description of them.

The QXmlStreamWriter is a streaming API that takes care of prefixing namespaces, when the namespaceUri is specified when writing elements or attributes.

Classes that Provide Serialization

<QtCborCommon> Contains definitions common to both the streaming classes (QCborStreamReader and QCborStreamWriter) and to QCborValue
QCborArray 用於保持 CBOR (簡明二進製對象錶示) 元素的數組
QCborMap 用於保持以 CBOR 錶示的關聯容器
QCborStreamReader 操作 QByteArray 或 QIODevice 的簡單 CBOR 流解碼器
QCborStreamWriter 操作單嚮流的簡單 CBOR 編碼器
QCborValue 封裝值在 CBOR 中
QDataStream 把二進製數據序列化到 QIODevice
QJsonArray 封裝 JSON 數組
QJsonDocument 讀寫 JSON 文檔的辦法
QJsonObject 封裝 JSON 對象
QJsonParseError 用於在 JSON 剖析期間報告錯誤
QJsonValue 把值封裝在 JSON 中
QTextStream 用於讀寫文本的方便接口
QXmlStreamReader 用於憑藉簡單流化 API 讀取格式良好的 XML 的快速剖析器
QXmlStreamWriter 采用簡單流化 API 的 XML 寫入器