本文介绍了通过QJsonObject进行Foreach以获取键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何通过 QJsonObject
通过 foreach
获取C ++中的键/值对吗?到目前为止,我只能获得价值.
I am wondering how I would foreach
through a QJsonObject
to get the key/value pairs in C++? So far, I am only able to get the 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"
}
推荐答案
John已经给出了答案.使用keys(),一个完整的可行解决方案将是:
John already gave the answer. Using keys() a complete working solution would be:
#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();
}
这篇关于通过QJsonObject进行Foreach以获取键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!