利用qt写一段获取json数据的代码
时间: 2023-04-03 19:00:55 浏览: 106
Qt关于json文件的简单实例代码
可以使用Qt自带的网络模块QNetworkAccessManager来获取json数据,示例代码如下:
```cpp
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager manager;
QNetworkRequest request(QUrl("http://example.com/data.json"));
QNetworkReply *reply = manager.get(request);
QObject::connect(reply, &QNetworkReply::finished, [&](){
QByteArray data = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject obj = doc.object();
QJsonArray arr = obj["data"].toArray();
for (int i = ; i < arr.size(); i++) {
QJsonObject item = arr[i].toObject();
QString name = item["name"].toString();
int age = item["age"].toInt();
qDebug() << "name:" << name << ", age:" << age;
}
reply->deleteLater();
QCoreApplication::quit();
});
return a.exec();
}
```
以上代码会从"http://example.com/data.json"获取json数据,并解析其中的"data"数组,输出每个元素的"name"和"age"字段。
阅读全文