我想知道如何foreach
通过QJsonObject
来获取C ++中的键/值对?到目前为止,我只能获得价值。
//main.cpp
QFile file(":/geoip.json");
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
file.close();
QJsonDocument doc(QJsonDocument::fromJson(rawData));
QJsonObject json = doc.object();
foreach(const QJsonValue &value, json) {
QJsonObject obj = value.toObject();
qDebug() << value;
}
//geoip.json
{
"Afghanistan": "58.147.159.255",
"Albania": "31.22.63.255",
"Algeria": "105.235.143.255",
"American Samoa": "202.70.115.241",
"Andorra": "109.111.127.255",
"Angola": "105.175.255.255",
"Anguilla": "208.66.50.44",
"Antarctica": "46.36.195.10"
}
答案 0 :(得分:5)
#include <QCoreApplication>
#include <QFile>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//main.cpp
QFile file("path/to/geoip.json");
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
file.close();
QJsonDocument doc(QJsonDocument::fromJson(rawData));
QJsonObject json = doc.object();
foreach(const QString& key, json.keys()) {
QJsonValue value = json.value(key);
qDebug() << "Key = " << key << ", Value = " << value.toString();
}
return a.exec();
}