Foreach通过QJsonObject获取键/值对

时间:2016-11-28 17:53:26

标签: c++ qt

我想知道如何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"
}

1 个答案:

答案 0 :(得分:5)

约翰已经给出了答案。使用keys()一个完整的工作解决方案是:

#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();
}