Qt中的JsonFormat是一个枚举类型,用于指定JSON文本的格式化方式。它有以下几个值:
JsonFormat::Compact:紧凑格式,将JSON文本压缩成一行。
JsonFormat::Indented:缩进格式,对JSON文本进行缩进。
JsonFormat::Indented | JsonFormat::EscapeUnicode:带有转义Unicode字符的缩进格式。
JsonFormat::Indented | JsonFormat::EnsureAscii:确保输出的文本只包含ASCII字符。
JsonFormat::Indented | JsonFormat::EscapeNonAscii:转义所有非ASCII字符的缩进格式。
下面是一个使用JsonDocument和JsonFormat输出JSON文本的例子:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建一个JSON对象
QJsonObject obj;
obj["name"] = "John";
obj["age"] = 30;
obj["married"] = false;
// 将JSON对象转换为文档
QJsonDocument doc(obj);
// 输出紧凑格式的JSON文本
qDebug() << doc.toJson(QJsonDocument::Compact);
// 输出缩进格式的JSON文本
qDebug() << doc.toJson(QJsonDocument::Indented);
return a.exec();
}
这个例子中,我们首先创建了一个包含三个属性(name、age和married)的JSON对象。然后通过QJsonDocument将其转换为JSON文档,并使用toJson函数输出不同格式的JSON字符串。