IT评测·应用市场-qidao123.com技术社区
标题:
qt-C++笔记之使用qDebug().noquote()优美地格式化打印json
[打印本页]
作者:
笑看天下无敌手
时间:
2024-7-24 08:07
标题:
qt-C++笔记之使用qDebug().noquote()优美地格式化打印json
qt-C++笔记之使用qDebug().noquote()优美地格式化打印json
code review!
在Qt中,可以使用QJsonDocument和QJsonObject来处置惩罚和格式化JSON数据。为了优美地格式化打印JSON数据,可以使用QJsonDocument::toJson()方法,并将其结果通报给qDebug().noquote()举行输出。
以下是一个示例代码,演示如何实现这一点:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建一个JSON对象
QJsonObject jsonObj;
jsonObj["name"] = "John Doe";
jsonObj["age"] = 30;
jsonObj["married"] = true;
// 创建一个JSON数组
QJsonArray children;
children.append("Jane");
children.append("Doe");
// 添加数组到JSON对象中
jsonObj["children"] = children;
// 将JSON对象转换为QJsonDocument
QJsonDocument jsonDoc(jsonObj);
// 格式化并打印JSON
qDebug().noquote() << jsonDoc.toJson(QJsonDocument::Indented);
return a.exec();
}
复制代码
输出示例
运行上述代码后,您将会在控制台看到格式化后的JSON输出,如下所示:
{
"name": "John Doe",
"age": 30,
"married": true,
"children": [
"Jane",
"Doe"
]
}
复制代码
在这个示例中,QJsonDocument::toJson(QJsonDocument::Indented)方法用于将JSON文档转换为带有缩进的格式化字符串,然后通过qDebug().noquote()输出到控制台。这种方式可以使JSON数据更加易读,方便调试和检察。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/)
Powered by Discuz! X3.4