欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > qt-C++笔记之使用qDebug().noquote()优美地格式化打印json

qt-C++笔记之使用qDebug().noquote()优美地格式化打印json

2024/10/24 8:25:41 来源:https://blog.csdn.net/weixin_43297891/article/details/140597158  浏览:    关键词:qt-C++笔记之使用qDebug().noquote()优美地格式化打印json

qt-C++笔记之使用qDebug().noquote()优美地格式化打印json

code review!

在Qt中,可以使用QJsonDocumentQJsonObject来处理和格式化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对象转换为QJsonDocumentQJsonDocument jsonDoc(jsonObj);// 格式化并打印JSONqDebug().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数据更加易读,方便调试和查看。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com