在Qt 6中,JSON解析可以使用Qt提供的QJsonDocument类来完成。下面是一个简单的示例代码,演示如何解析JSON数据:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
// JSON字符串
QString jsonString = "{\"name\": \"John\", \"age\": 30}";
// 解析JSON字符串为QJsonDocument对象
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8(), &error);
if (error.error != QJsonParseError::NoError) {
qWarning() << "Failed to parse JSON:" << error.errorString();
return -1;
}
// 检查是否为Object类型
if (!jsonDoc.isObject()) {
qWarning() << "JSON is not an object";
return -1;
}
// 获取根节点对象
QJsonObject jsonObj = jsonDoc.object();
// 获取name和age字段值
QString name = jsonObj["name"].toString();
int age = jsonObj["age"].toInt();
qDebug() << "Name:" << name;
qDebug() << "Age:" << age;
return app.exec();
}
以上代码将会输出以下结果:
Name: "John"
Age: 30
你可以根据自己的需求修改和扩展该示例。记得在项目文件(.pro)中添加 QT += core
来引入必要的模块。
内容由零声教学AI助手提供,问题来源于学员提问