1

我使用 qt 5.0 及其支持 QJsonObject QJsonDocument 和 QJsonArray 等类。在我的程序中,我需要序列化 ​​json 数组并将其转换为 qstring/qbytearray 但我没有在这些类中找到任何序列化或编码方法。有什么方法可以使用包含的 qt 5.0 序列化数据。库?我找到了这个例子:

QVariant id(1), name("John Doe");
QJsonObject json;

json["Name"] = name.toString();
json.insert("id", id.toInt());

但我找不到如何从中制作数组。

4

2 回答 2

0

问题关闭。使用 QJsonDocument::toJson 从 QJsonObject 获取数据。

于 2013-07-16T22:21:25.643 回答
0

I think the secret is that when serializing to JSON, Qt writes out a UTF-8 binary encoded version of the text into a QByteArray. You can recover the string using QString::fromUtf8. Also, even though toJson writes out a QByteArray it is not a true binary representation; as I just mentioned, it is the bytes of the UTF-8 encoded string representation of the JSON. For binary serialization you must use either Qt's own QJsonDocument::toBinaryData or find a BSON library.

Text serialization

Use QJsonDocument::toJson to serialize as text via a QString, and QJsonDocument::fromJson to deserialize from text.

Tip: Consider passing the QJsonDocument::Compact format option to get compact JSON output during serialization.

To QString

QString json = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));

From QString

QJsonDocument doc = QJsonDocument::fromJson(json);

Binary serialization

Use QJsonDocument::toBinaryData to serialize as binary via a QByteArray, and QJsonDocument::fromBinaryData to deserialize from binary.

Caveat: The binary format used by the above functions is Qt's own binary format (qbjs) so may not be suitable for interoperation with other binary formats such as BSON. For that, you might want to look into choosing a BSON implementation.

To QByteArray

QByteArray bytes = doc.toBinaryData();

From QByteArray

QJsonDocument doc = QJsonDocument::fromBinaryData(bytes);
于 2019-06-06T14:48:32.603 回答