在Qt中解析JSON字符串可以使用QJsonDocument和QJsonObject类。以下是一个示例代码,展示了如何解析包含字符串、对象和整数的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, \"address\": {\"city\": \"New York\", \"country\": \"USA\"}}";
// 解析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字段值
QString name = jsonObj["name"].toString();
qDebug() << "Name:" << name;
// 获取age字段值(整数)
int age = jsonObj["age"].toInt();
qDebug() << "Age:" << age;
// 获取address字段值(对象)
if(jsonObj.contains("address") && jsonObj["address"].isObject()){
QJsonObject addressObj = jsonObj["address"].toObject();
QString city = addressObj["city"].toString();
QString country = addressObj["country"].toString();
qDebug() << "City:" << city;
qDebug() << "Country:" << country;
}
return app.exec();
}
以上代码将会输出以下结果:
Name: "John"
Age: 30
City: "New York"
Country: "USA"
这个示例演示了如何解析包含字符串、对象和整数的JSON数据,并将对应字段的值提取出来。你可以根据自己的需要对示例代码进行修改和扩展。同样,记得在项目文件(.pro)中添加 QT += core
来引入必要的模块。
内容由零声教学AI助手提供,问题来源于学员提问