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

发布于:2024-07-24 ⋅ 阅读:(110) ⋅ 点赞:(0)

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对象转换为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数据更加易读,方便调试和查看。


网站公告

今日签到

点亮在社区的每一天
去签到