我想知道如何通过foreachQJsonObject获得C++中的键/值对吗?到目前为止,我只能获得值(value)。

//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"
}

最佳答案

约翰已经给出了答案。使用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();
}

关于c++ - 通过QJsonObject进行Foreach以获取键/值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40850552/

10-11 19:29