我正在尝试解析 this JSON Web-API 使用 Qt5 和 C++ 使用 QJsonDocument 和 QJsonObject 见 here .但是我无法访问 QJsonObject 的 JSON 值。
这是我到目前为止尝试过的:
// Contains the whole API as QString...
QString data = QString(reply->readAll());
// Reads the JSON as QJsonDocument...
QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
// Reads the JSON as QJsonObject...
QJsonObject jsonObject = jsonResponse.object();
现在我已经准备好了我的对象,但是试图访问 JSON 的值却以某种方式失败了:
// This returns an empty string ""!?!
qDebug() << jsonObject.value("success").toString();
嗯,也许我把 key 弄错了:
// Let's check the keys...
QStringList stringList = jsonObject.keys();
for (QStringList::Iterator it = stringList.begin(); it != stringList.end(); ++it)
{
// This returns "success" and "return" - huh!?!
qDebug() << *it;
}
好的,按键已经设置好了,为什么不能用?
// Let's check the values by using the keys directly...
for (QStringList::Iterator it = stringList.begin(); it != stringList.end(); ++it)
{
// This returns empty strings "" and "" - now what?!?
qDebug() << jsonObject.value(*it).toString();
}
这又是毫无意义的。我不明白为什么我不能通过键访问 JSON 对象的值。有什么想法吗?
我在其他 JSON API(例如 this 之一)上尝试了完全相同的代码,没有任何问题。我完全被困在这里。
最佳答案
这是我的 Qt5 Json 解析 Cryptsy API 的解决方案。
QEventLoop loopEvent;
QNetworkAccessManager namMNGR;
QObject::connect(&namMNGR, SIGNAL(finished(QNetworkReply*)), &loopEvent, SLOT(quit()));
QNetworkRequest req(QUrl(QString("http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=%1").arg(marketID)));
QNetworkReply *reply = namMNGR.get(req);
loopEvent.exec();
//Json API parsing begins.
QString jsonSTR = reply->readAll();
if (!(reply->error() == QNetworkReply::NoError)) {
delete reply; //API Connection Problem.
}
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonSTR.toUtf8());
QJsonObject obj1 = jsonDocument.object();
QJsonValue val1 = obj1.value(obj1.keys().first());
QJsonObject obj2 = val1.toObject();
QJsonValue val2 = obj2.value(obj2.keys().first());
QJsonObject obj3 = val2.toObject();
QJsonValue marketDataValue = obj3.value(obj3.keys().first());
QJsonObject marketDataObject = marketDataValue.toObject();
QJsonArray sellordersArray = marketDataObject["sellorders"].toArray();
您是否设法从 Qt5 获取经过身份验证的 POST API 数据?我正在尝试弄清楚该怎么做。
关于c++ - 为什么我不能用 Qt5/C++ 解析 Cryptsy JSON API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537907/